基于业务需求,需借助Gin框架封装通用功能,在此记录Gin使用笔记。(在线许愿:有机会学习Gin源码❤️🩹)
Gin笔记
一、基本操作及测试
import (
"github.com/gin-gonic/gin"
)
【代码】简单的启动示例
func main() {
api := gin.Default()
api.GET("/test", GetTestEndpoint)
api.Run(":8080")
}
func GetTestEndpoint(c *gin.Context) {
resp := map[string]string{"hello": "world"}
c.JSON(200, resp)
}
【终端】运行试试看
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
- using env: export GIN_MODE=release
- using code: gin.SetMode(gin.ReleaseMode)
[GIN-debug] GET /test --> main.GetTestEndpoint (3 handlers)
[GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.
[GIN-debug] Listening and serving HTTP on :8080
程序等待,这是因为没有触发/test
,下面我们模拟触发
搬出我们Apifox
【测试】
本地环境:127.0.0.1:8080
新建GET接口,参数:/test
触发:发送
【终端】
【前端】
【代码】添加中间件示例
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.Use(TestMiddleware())
r.GET("/test", TestPrint(), func(c *gin.Context) {
c.JSON(200, map[string]interface{}{
"code": 1,
"msg": "【Hello world!】",
})
})
r.Run(":8080")
}
func TestMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
path := c.FullPath()
method := c.Request.Method
fmt.Println("请求路径:", path, "请求方法:", method)
}
}
func TestPrint() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.WriteString("Hello!")
c.Next()
fmt.Println("请求状态码:", c.Writer.Status())
}
}
【终端】运行加载
【测试】
本地环境:127.0.0.1:8080
新建GET接口,参数:/test
触发:发送
【终端】
【前端】