我想用golang实现MVC。但似乎很难实现我想要的。 在 Testcontroller.go 中我有:
func (c *TestController) Test() {
//
}
func (c *TestController) Index() {
//
}
只有一个 Controller ,我可以使用 reflect.ValueOf(TestController{}).MethodByName().Call() 来执行该功能。 现在我想添加另一个 Controller 。但似乎我无法通过不同的字符串新建不同的实例:
controllerName := strings.Split(r.URL.Path, "/")
controller = reflect.ValueOf(controllerName[1])
我知道这是完全错误的,但我希望如果 controllerName == "Test"我能得到一个 TestController 实例,如果 controllerName == "Index"我能得到一个 IndexController 实例,使用反射似乎无法实现我想要的。有什么办法吗? 非常感谢!
最佳答案
你可以这样做:
为你的 Controller 定义一个接口(interface):
type Controller interface {
// Route returns the root route for that controller
Route() string
}
在 Controller 中实现它:
// 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() {
//
}
在我们的应用程序中,创建您的 Controller 的注册表,您可以查找它们:
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])
}
}
关于model-view-controller - 我可以在golang中根据字符串实例化不同的类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28134710/