Golang gorilla mux可以从类或文件中定义路由。

huangapple go评论86阅读模式
英文:

Golang gorilla mux routes from class or file

问题

我正在玩弄gorilla mux,并希望将所有应用程序的路由设置在一个文件中,以免在主文件中填充大量路由。理想情况下,我希望还可以从数据库中获取路由。

gorilla mux是用于这个目的的正确包吗?还是还有其他要考虑的东西?这个能做到吗?

英文:

I'm playing around with gorilla mux and would like to set all of the application routes in a file so they don't fill up the main file with a bunch of routes. Ideally I would like to have the optional ability to even pull the routes from a database too.

Is gorilla mux the right package to use for this or is there something else to look at? Is this something that can be done?

答案1

得分: 1

gorilla mux不会这样做,而且在Go语言中的路由库中也不常见,因为Go是一种静态类型和编译语言。

如果你有一个简单的一对一的处理程序映射,你可以很容易地做到这一点:

// 通过名称在映射中注册处理程序或处理程序函数:
handlerMap := make(map[string]*http.Handler)
// 或者
handlerFuncMap := make(map[string]func(http.ResponseWriter, *http.Request))

handlerMap["myHandler"] = myHandler

// 现在你可以遍历你的配置值,并将它们分配给路由器
for path, handler := range routes {
myRouter.Handler(path, handlerMap[handler])
}

英文:

gorilla mux doesn't do this, and it's not common for routing libraries in Go, since it's statically typed and compiled language.

If you have a simple 1:1 mapping of handlers, you can do this fairly easily:

// register the handlers or handler_funcs by name in a map:
handlerMap := make(map[string]*http.Handler)
// OR
handlerFuncMap := make(map[string]func(http.ResponseWriter, *http.Request))

handlerMap["myHandler"] = myHandler

// now you can iterate over you config values and assign them to a router
for path, handler := range routes {
    myRouter.Handler(path, handlerMap[handler])
}

huangapple
  • 本文由 发表于 2014年7月18日 01:24:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/24809833.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定