dongying9712
2015-01-25 08:45
浏览 229
已采纳

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

I want to implement MVC in golang. But it seems like hard to achieve what I want. in Testcontroller.go I have:

func (c *TestController) Test() {
    //
}

func (c *TestController) Index() {
    //
}

With only a controller, I can use reflect.ValueOf(TestController{}).MethodByName().Call() to execute that function. now I want to add another controller. but It seems like I can't new different instance by different string:

controllerName := strings.Split(r.URL.Path, "/")
controller = reflect.ValueOf(controllerName[1])

I know this is totaly wrong, but I hope I can get a TestController instance if controllerName == "Test" and get a IndexController instance if controllerName == "Index", using reflect seems can't achieve what I want. Is there any way to do is? Thank you very much!

图片转代码服务由CSDN问答提供 功能建议

我想在golang中实现MVC。 但似乎很难实现我想要的。 在Testcontroller.go中,我拥有:

  func(c * TestController)Test(){
 // 
}  
 
func(c * TestController)Index(){
 // 
} 
   
 
 

只有一个控制器,我才能使用reflect.ValueOf(TestController) {})。MethodByName()。Call()执行该函数。 我想添加另一个控制器。 但是似乎我不能通过不同的字符串来创建新的实例:

  controllerName:= strings.Split(r.URL.Path,“ /”)
controller =体现 .ValueOf(controllerName [1])
   
 
 

我知道这是完全错误的,但是我希望如果controllerName ==“ Test”并可以得到一个TestController实例, IndexController实例,如果controllerName ==“ Index”,使用反射似乎无法实现我想要的。 非常感谢您!

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongyue5686 2015-01-25 12:14
    已采纳

    You could do something like that:

    Define an interface for your controllers:

    type Controller interface {
       // Route returns the root route for that controller
       Route() string
    }
    

    In a controller just implement it:

    // 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() {
        //
    }
    

    In our app, create a registry of your controllers, and you can look them up:

    var controllers = make([]Controller, 0)
    
    // register them somehow
    

    And now in the serving process:

    // 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])
        }
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题