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!
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])
}
}