Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid initialization loop in Go

Tags:

go

When I try to compile this code:

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
)

func main() {
    fmt.Println("Hello, playground")
}

const (
    GET    = "GET"
    POST   = "POST"
    PUT    = "PUT"
    DELETE = "DELETE"
)

type Route struct {
    Name        string           `json:"name"`
    Method      string           `json:"method"`
    Pattern     string           `json:"pattern"`
    HandlerFunc http.HandlerFunc `json:"-"`
}

type Routes []Route

var routes = Routes{
    Route{
        Name:        "GetRoutes",
        Method:      GET,
        Pattern:     "/routes",
        HandlerFunc: GetRoutes,
    },
}

func GetRoutes(res http.ResponseWriter, req *http.Request) {
    if err := json.NewEncoder(res).Encode(routes); err != nil {
        panic(err)
    }
}

Playground

the compiler returns this error message:

main.go:36: initialization loop:
    main.go:36 routes refers to
    main.go:38 GetRoutes refers to
    main.go:36 routes

The goal of this code is to return all the routes of my API in a JSON when a client application executes a GET request on the the /routes route.

Any idea on how can I find a clean workaround to this problem?

like image 485
Jean Lebrument Avatar asked Dec 11 '22 22:12

Jean Lebrument


2 Answers

Assign the value later within init(). This will let the GetRoutes function be initialized first, then it can be assigned.

type Routes []Route

var routes Routes

func init() {
    routes = Routes{
        Route{
            Name:        "GetRoutes",
            Method:      GET,
            Pattern:     "/routes",
            HandlerFunc: GetRoutes,
        },
    }
}
like image 167
JimB Avatar answered Dec 29 '22 00:12

JimB


Use init:

var routes Routes

func init() {
    routes = Routes{
        Route{
            Name:        "GetRoutes",
            Method:      GET,
            Pattern:     "/routes",
            HandlerFunc: GetRoutes,
        },
    }
}
like image 21
Ainar-G Avatar answered Dec 29 '22 00:12

Ainar-G