【发布时间】:2015-05-22 02:19:56
【问题描述】:
我想映射每条路由及其请求类型(GET、POST、PUT、...),以便为我的 restful API 生成类似于 JSON 格式的 sitemap.xml。
Goji 使用函数来创建新路线。我可以将路径和处理程序存储在地图中。
我的方法是这样的,除了编译器给出了以下初始化循环错误,因为sitemap 和routes 相互引用(路由图包含应该 marhsall 本身的处理程序站点地图)。
main.go:18: initialization loop:
main.go:18 routes refers to
main.go:41 sitemap refers to
main.go:18 routes
这可以以更惯用的方式实现吗?
package main
import (
"encoding/json"
"net/http"
"github.com/zenazn/goji"
"github.com/zenazn/goji/web"
)
var routes = []Route{
Route{"Get", "/index", hello},
Route{"Get", "/sitemap", sitemap},
}
type Route struct {
Method string `json:"method"`
Pattern string `json:"pattern"`
Handler web.HandlerType `json:"-"`
}
func NewRoute(method, pattern string, handler web.HandlerType) {
switch method {
case "Get", "get":
goji.DefaultMux.Get(pattern, handler)
case "Post", "post":
goji.DefaultMux.Post(pattern, handler)
// and so on...
}
}
func hello(c web.C, w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello world"))
}
func sitemap(c web.C, w http.ResponseWriter, r *http.Request) {
// BUG: sitemap tries to marshall itself recursively
resp, _ := json.MarshalIndent(routes, "", " ")
// some error handling...
w.Write(resp)
}
func main() {
for _, r := range routes {
NewRoute(r.Method, r.Pattern, r.Handler)
}
goji.Serve()
}
【问题讨论】:
-
通常我会这样做,但我不想让示例尽可能简单。感谢
init()的提示 -
wrt 错误,没关系;只是我在“真实”代码中经常看到这种情况,可能来自天真的人剪切-粘贴,这就是为什么我有时会指出它,我更喜欢将示例简化为不亚于检查错误的评论(即@ 987654327@ 或类似的)
-
我添加了一个注解。
-
你会坚持使用 switch-case 方法吗?
-
我不知道/使用
goji,所以我不熟悉它。但是,您的两种情况调用具有相同签名的函数,因此也许您可以考虑使用接口或type x func(string, web.Handler),作为参数或映射条目(或Route的字段)或其他。由于这可能与问题无关或太健谈,如果您愿意,我们可以将其发送至 Stack Overflow Chat。