[TOC]
变量说明:
ctx = gin.Context
r := gin.Engine() or r:= gin.Default()
注意事项
初始化相关
- 禁止带颜色的console输出:
gin.DisableConsoleColor()
- 运行模式,prod环境要记得设置mode=release
export GIN_MODE=release
gin.SetMode(gin.ReleaseMode)
- mode=release或通过
gin.Default()
创建引擎时,默认有如下操作:- Logger middleware will write the logs to gin.DefaultWriter and By default gin.DefaultWriter = os.Stdout
- Recovery middleware recovers from any panics and writes a 500 if there was one.
- 设置KEEP_ALIVE:
httpServer := &http.Server{Handler: router,}
- 写路由时不要带尾巴的"/"
- json采用json-iter:
go build -tags=jsoniter
路由
- 路由匹配模式只有两种,":"和"*", 注意事项,"*"只能放在末尾。具体参考:
- 原理(named parameters & catch-all parameters):https://github.com/julienschmidt/httprouter#named-parameters
- 可采用的regex方案: https://github.com/gin-gonic/gin/issues/229
中间键
- 中间键有以下几种运用方式:
- 单个中间键:
engine.Use(middleware)
- 组中间键:
g = engine.Group("/")
g.Use(middleware)
- 单个中间键:
- 内置的中间键
- gin.Logger()
- gin.Recovery()
Model binding and validation
- 预备知识点:https://www.jianshu.com/p/2f38fdfcfbec,
- 相关的基本概念:
- Binding 接口:
- Name(): 声明是属于哪类型,
json, xml, form-urlencoded, multipart/form-data, msgpack, protobuf
- Bind(): 提供给gin.Context 调用,BindJSON --> MustBindWith --> ShouldBindWith --> Bind() --> jsonBinding/xmlBinding/protobufBinding... --> validate() --> StructValidator --> validator.defaultValidator . 原理本质上将所有的数据格式,转化成struct, 再调用validator.defaultValidator.ValidateStruct(obj)
- Name(): 声明是属于哪类型,
- StructValidator: validator in go,StructValidator负责调用validator里面的内容
- Binding 接口:
- 在gin中的使用步骤:
- 声明struct,并注释好相关的tag,tag的标准与validator相同.
- 调用Bind族函数,有如下方法:
- 最智能的方法:
ctc.Bind(&obj)
, 会根据Content-Type自动识别,前提这些类型必须是gin内部已经实现好了,具体看: - 直接调用封装好的通用的验证方法如json: ctx.BindJSON(&jsonStruct)
- xml貌似gin没封闭好:ctx.MustBindWith(&xml, binding.XML). MustBindWith()如果验证失败,会调用
ctx.AbortWithError(400, err).SetType(ErrorTypeBind)
设置返回代码400. - Form: ctx.MustBindWith(&form, binding.Form)
- 内置常见的几种验证: https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L62:1
- 最智能的方法:
middleware
- 每个endpoint 维护一个 Handlers (类型: gin.HandlersChain),如果要增加全局的middleware,必须在最开始执行:
r.Use(middleware)
- 为每个endpoint 增加middleware:
r.Get(endponit, middleware1, middleware2, your_bussiness_func)
- 用于组的middleware: group := r.Group("/admin", middleware1, m2, ...)
启动方式
基于内建的http方式启动
router := gin.Default()
http.ListenAndServe(":8080", router)
或者
router := gin.Default()
s := &http.Server{
Addr: ":8080",
Handler: router,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
s.ListenAndServe()
gin 方式启动
r := gin.New()
r.Run()