1 回答
TA贡献1820条经验 获得超2个赞
你可以这样做:
为您的控制器定义一个接口:
type Controller interface {
// Route returns the root route for that controller
Route() string
}
在控制器中只需实现它:
// this tells our app what's the route for this controller
func (c *TestController) Route() string {
return "test"
}
func (c *TestController) Test() {
//
}
func (c *TestController) Index() {
//
}
在我们的应用程序中,为您的控制器创建一个注册表,您可以查找它们:
var controllers = make([]Controller, 0)
// register them somehow
现在在服务过程中:
// assuming the path is /<controller>/<method>
controllerName := strings.Split(r.URL.Path, "/")
// again, you can use a map here, but for a few controllers it's not worth it probably
for _, c := range controllers {
if c.Route() == controllerName[1] {
// do what you did in the single controller example
callControllerWithReflection(c, controllerName[2])
}
}
- 1 回答
- 0 关注
- 166 浏览
添加回答
举报