model-view-controller - 我可以在golang中根据字符串实例化不同的类型吗?

标签 model-view-controller go

我想用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/

相关文章:

java - 模型类(在 MVC 中)应该使用静态方法还是实例方法?

model-view-controller - MVC模式中的 "model"是什么?

运行时错误 : “assignment to entry in nil map”

JAVA MVC 访问数据库

asp.net-mvc - 为什么是 Model View Controller 而不是适配器 View Controller ? "M"或模型不清晰

json - 无法使用未知键解码嵌套的 json

Go syscall 调用窗口

Go 项目不从 github 中提取导入更新

Golang 混合赋值和声明

javascript - Sencha 2.x MVC : Get element by id