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

我可以根据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!

  • 写回答

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])
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于这个问题的代码运行
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败