go_dreamfactory/modules/version/api.go

58 lines
1.5 KiB
Go

package version
import (
"go_dreamfactory/lego/core"
"go_dreamfactory/lego/core/cbase"
"go_dreamfactory/lego/sys/gin"
"go_dreamfactory/lego/sys/gin/engine"
"reflect"
"strings"
)
/*
web api 服务组件
*/
type Api_Comp struct {
cbase.ModuleCompBase
options *Options //模块参数
module *Version //当前模块对象
gin gin.ISys //gin 框架 web的热门框架
}
// 组件初始化接口 启动web服务 并注册api
func (this *Api_Comp) Init(service core.IService, module core.IModule, comp core.IModuleComp, options core.IModuleOptions) (err error) {
err = this.ModuleCompBase.Init(service, module, comp, options)
this.options = options.(*Options)
this.module = module.(*Version)
if this.gin, err = gin.NewSys(gin.SetListenPort(this.options.Port)); err != nil {
return
}
this.suitableMethods() //发射注册api
return
}
func (this *Api_Comp) suitableMethods() {
typ := reflect.TypeOf(this)
vof := reflect.ValueOf(this)
for m := 0; m < typ.NumMethod(); m++ {
method := typ.Method(m)
mname := method.Name
mtype := method.Type
if method.PkgPath != "" {
continue
}
if mtype.NumIn() != 2 {
continue
}
context := mtype.In(1)
if context.String() != "*engine.Context" {
continue
}
if mtype.NumOut() != 0 {
continue
}
this.gin.POST(strings.ToLower(mname), vof.MethodByName(mname).Interface().(func(*engine.Context)))
this.gin.GET(strings.ToLower(mname), vof.MethodByName(mname).Interface().(func(*engine.Context)))
}
}