当我尝试编译此代码时:package mainimport ( "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 []Routevar 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编译器返回此错误消息:main.go:36: initialization loop: main.go:36 routes refers to main.go:38 GetRoutes refers to main.go:36 routes此代码的目标是当客户端应用程序对/routes路由执行 GET 请求时,以 JSON 形式返回我的 API 的所有路由。关于如何找到解决此问题的干净方法的任何想法?
2 回答
慕斯709654
TA贡献1840条经验 获得超5个赞
稍后在init(). 这将使GetRoutes函数首先被初始化,然后它可以被分配。
type Routes []Route
var routes Routes
func init() {
routes = Routes{
Route{
Name: "GetRoutes",
Method: GET,
Pattern: "/routes",
HandlerFunc: GetRoutes,
},
}
}
慕哥9229398
TA贡献1877条经验 获得超6个赞
使用init:
var routes Routes
func init() {
routes = Routes{
Route{
Name: "GetRoutes",
Method: GET,
Pattern: "/routes",
HandlerFunc: GetRoutes,
},
}
}
- 2 回答
- 0 关注
- 143 浏览
添加回答
举报
0/150
提交
取消