Go Revel 中是如何实现根据路由动态加载控制器的?

tankerwng · September 14, 2015 · Last by tankerwng replied at September 15, 2015 · 8053 hits

如题目内容,controller 文件夹下有各种 controller,只需在 conf/routes 中对应路由表,各个 controller 实例会自动生成。 revel/controller.go中:

func RegisterController(c interface{}, methods []*MethodType) {
    // De-star the controller type
    // (e.g. given TypeOf((*Application)(nil)), want TypeOf(Application))
    var t reflect.Type = reflect.TypeOf(c)
    var elem reflect.Type = t.Elem()
    // De-star all of the method arg types too.
    for _, m := range methods {
        m.lowerName = strings.ToLower(m.Name)
        for _, arg := range m.Args {
            arg.Type = arg.Type.Elem()
        }
    }
    controllers[strings.ToLower(elem.Name())] = &ControllerType{
        Type:              elem,
        Methods:           methods,
        ControllerIndexes: findControllers(elem),
    }
    TRACE.Printf("Registered controller: %s", elem.Name())
}

RegisterController 方法在哪儿调用啊,没找到。 我很想知道参数 c interface{}的 type 是如何赋值的。

revel/cmd/harness/build.go#369

revel.RegisterController((*{{index $.ImportPaths .ImportPath}}.{{.StructName}})(nil)...

@rei ,呵呵,不好意思,下次注意。

@huacnlee ,谢谢了,还是 ruby China 强哈

#4 楼 @tankerwng 开始研究 go 了?

@zmbacker ,呵呵,嗯,没事想研究研究,下个项目想用它。

好吧,我败了,golang 果然是不是 ruby,http://stackoverflow.com/questions/23030884/is-there-a-way-to-create-an-instance-of-a-struct-from-a-string ,revel 也不是纯动态了化,还是得知道 structs 有哪些,只不过不用手动写,而是通过 go/ast,“打印了”出来。

You need to Sign in before reply, if you don't have an account, please Sign up first.