How to avoid the initialization loop in 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)
}
}
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 purpose of this code is to return all my API routes to JSON when the client application makes a GET request on the trace /routes
.
Any idea on how I can find a workaround for this problem?
+3
source to share
2 answers
Assign a value later in init()
. This will allow the function to be initialized first GetRoutes
, then it can be assigned.
type Routes []Route
var routes Routes
func init() {
routes = Routes{
Route{
Name: "GetRoutes",
Method: GET,
Pattern: "/routes",
HandlerFunc: GetRoutes,
},
}
}
+6
source to share