控制器和请求方法
控制器
新生成的控制只有一个空的接结构体, 例如 app/http/api/public/controller.go
, 你可以在这个结构体上注入任何内容,例如配置,例如logic下的结构体等等;是用在专门存放公共内容的地方
package public
import "github.com/go-home-admin/home/bootstrap/services"
// Controller @Bean
type Controller struct {
// 注入配置
name string `inject:"config, app.name"`
// 注入一个mysql连接
mysql *gorm.DB `inject:"database, mysql"`
// 注入一个redis连接
rds *services.Redis `inject:"database, redis"`
}
每次修改注释, 都应该执行一下命令make gen
,用来生成依赖代码,当然如果你不怕麻烦,也是可以手写依赖的
请求方法
新生成的请求方法在 app/http/api/public/test_action.go
,里面默认有两个函数; Test() 是已经绑定参数和限制响应格式的友好函数,一般都是在这里面写业务,如果有特别的内容,proto无法定义您的格式时候,也可以直接在GinHandleTest写gin原始的处理,跳过proto。
package public
import (
gin "github.com/gin-gonic/gin"
api "github.com/go-home-admin/go-admin/generate/proto/api"
http "github.com/go-home-admin/home/app/http"
)
// Test 测试接口2
func (receiver *Controller) Test(req *api.HomeRequest, ctx http.Context) (*api.HomeResponse, error) {
// TODO 这里写业务
return &api.HomeResponse{}, nil
}
// GinHandleTest gin原始路由处理
// http.Post(/test)
func (receiver *Controller) GinHandleTest(ctx *gin.Context) {
req := &api.HomeRequest{}
err := ctx.ShouldBind(req)
context := http.NewContext(ctx)
if err != nil {
context.Fail(err)
return
}
resp, err := receiver.Test(req, context)
if err != nil {
context.Fail(err)
return
}
context.Success(resp)
}
原始gin处理
你可以在app/http/kernel.go
编写原始的gin
api
处理
func (k *Kernel) Init() {
。。。其他代码
k.GET("/healthz", func(context *gin.Context) {
context.String(200, "ok")
})
}