Engine(路由器/入口) → HandlerFunc(处理函数) → Context(请求上下文)
// 经典模版
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{"msg": "pong"})
})
r.Run(":8080")
所有 Gin 的东西基本都能从这里长出来:
想加中间件:r.Use(...)
想分组:g := r.Group("/api")
想绑定参数:c.Param / c.Query / c.ShouldBindJSON
想返回:c.JSON / c.String / c.Status
建议你先只覆盖 80% 场景的 12 个:
路由/中间件
gin.Default() / gin.New()
r.Use(mw...)
r.GET/POST/...
r.Group("/xx")
取数据
c.Param("id")(路径参数)
c.Query("k")(query 参数)
c.GetHeader("Authorization")
c.ShouldBindJSON(&obj)(JSON body)
回数据
c.JSON(code, obj)
c.String(code, "text")
c.Status(code)
c.AbortWithStatusJSON(code, obj)(中断链路)
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
// 创建一个默认的路由引擎
r := gin.Default()
// 注册一个GET 路由: 访问/ping 返回JSON
r.GET("/ping", func(c *gin.Context) {
//c.JSON(200, map[string]interface{}{
// "message": "pong",
//})
// 上面的写法等同于下面的
c.JSON(http.StatusOK, gin.H{
"message": "pong",
})
})
// /hello?name=Tom
r.GET("/hello", func(c *gin.Context) {
// ? 后面的叫 查询参数(Query String):
//name 是参数名
//Tom 是参数值
//如果是 /hello?name=Tom&age=18:
//name → Tom
//age → 18
//c.Query("name") 做了什么?
//c.Query("name") 就是从 URL 的 query 里拿值:
name := c.Query("name") // 获取 query参数 在URL后面加上/hello?name=Tom 返回的结果就是 hello, Tom! 如果只访问/hello 就返回下面默认的 hello,world!
age := c.Query("age")
if name == "" {
name = "world"
}
if age == "" {
age = "18"
}
c.String(http.StatusOK, "hello, %s , age %s!", name, age)
})
r.Run()
}
评论 (0)