gin常用的http请求方法以及路由分组

常用的http请求方法

package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func main() {
	engine := gin.Default()
	engine.GET("/goods/find",handles)
	engine.POST("/goods/all",handles)
	engine.DELETE("/goods/delete",handles)
	engine.PUT("/goods/update",handles)
}

// 保证代码顺利编译;没有什么实际含义
func handles(context *gin.Context) {
	context.JSON(http.StatusOK,gin.H{
		"status":"OK",
	})
}

路由分组

上面的代码全部都是goods模块下一些路由.在我们实际的开发应用中我们希望能个各个功能模块的路由进行分组,同一个模块的不同路由带有同样的前缀

package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func main() {
	engine := gin.Default()
	goodsGroup := engine.Group("/goods")
	{
		goodsGroup.GET("/find",handles)
		goodsGroup.POST("/all",handles)
		goodsGroup.DELETE("/delete",handles)
		goodsGroup.PUT("/update",handles)
	}

}

// 保证代码顺利编译;没有什么实际含义
func handles(context *gin.Context) {
	context.JSON(http.StatusOK,gin.H{
		"status":"OK",
	})
}

使用路由分组以后, 路由更加的清晰,用花括号将同一分组的路由括起来,代码更有层次感;并且我们在针对某一组路由进行中间件权限校验的时候也比较的方便。


版权声明:本文为qq_43135259原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。