1、路由定义
func InitRouter() *gin.Engine {
router := gin.Default()
router.GET("/", controllers.IndexAction)
router.GET("/one", controllers.GetOneAction)
v2 := router.Group("v2")
v2.GET("/", controllers.Index2Action)
v2.GET("/one", controllers.GetOneAction)
return router
}
2、reques参数获取及返回值
func GetOneAction(ctx *gin.Context) {
id, _ := ctx.GetQuery("id")
intId, _ := strconv.Atoi(id)
var model models.User
res := model.GetOne(intId)
/*var pbUser cs.User
pbUser.Id = int32(res.Id)
pbUser.Age = string(res.Age)
pbUser.Name = res.Name
ctx.ProtoBuf(http.StatusOK, &pbUser)*/
ctx.JSON(http.StatusOK, res)
3、中间件(钩子函数)添加
//定义hooks
func Hook1(ctx *gin.Context) {
fmt.Println("hook1 is running!")
ctx.Next()
fmt.Println("hook1 is finished!")
}
//为单独的一个路由添加hook
router.GET("/", hooks.Hook1,controllers.IndexAction)
//为一个路由组添加hook
v2 := router.Group("v2")
v2.GET("/", controllers.Index2Action)
v2.GET("/one", controllers.GetOneAction)
v2.Use(hooks.Hook1)
//添加全局hook
router.Use(hooks.Hook1)
//添加多个hooks
router.Use(hooks.Hook1,hooks.Hook2)