一.路由组请求
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
func main() {
engine := gin.Default()
routeGroup := engine.Group("/user")
routeGroup.POST("/register", registerHandle)
routeGroup.POST("login", loginHandle)
routeGroup.DELETE("/:id", deleteHandle)
engine.Run()
}
func registerHandle(context *gin.Context) {
fullPath := "用户登录" + context.FullPath()
fmt.Println(context.FullPath())
context.Writer.WriteString(fullPath)
}
func loginHandle(context *gin.Context) {
fullPath := "用户登录" + context.FullPath()
fmt.Println(context.FullPath())
context.Writer.WriteString(fullPath)
}
func deleteHandle(context *gin.Context) {
fullPath := "用户删除" + context.FullPath()
userID := context.Param("id")
fmt.Println(context.FullPath() + userID)
context.Writer.WriteString(fullPath + " " + userID)
}
结果:
二.中间件
中间件在服务器段和具体的业务逻辑处理之间,包括的内容有:权限处理,认证处理等。
Gin的中间件:
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
func main() {
engine := gin.Default()
engine.GET("/query", Request(), func(context *gin.Context) {
context.JSON(404, map[string]interface{}{
"code": 1,
"msp": context.FullPath(),
})
})
engine.Run(":9000")
}
func Request() gin.HandlerFunc {
return func(context *gin.Context) {
path := context.FullPath()
method := context.Request.Method
fmt.Println("path请求:", path)
fmt.Println("method请求:", method)
fmt.Println("状态码:", context.Writer.Status())
fmt.Println()
context.Next()
fmt.Println("状态码:", context.Writer.Status())
}
}
context.Next()在作用:把代码分为两段,前面会首先执行,而后面的会等到具体代码执行后再执行。
结果:



