获取参数
Gin获取到的参数都输string
类型,需要手动转成int
类型
所有的请求实体都要明确使用tag标记uri, form, json
路由参数
/users/:id
可以使用c.Param("id")
获取
r.GET("/users/:id", func(c *gin.Context) {
id := c.Param("id")
c.String(200, "The user id is %s", id)
})
如果路径参数存在多个,例如:/:name/:id
,也可以定义结构体,通过ShouldBindUri
方式获取
package main
import "github.com/gin-gonic/gin"
type Person struct {
ID string `uri:"id" binding:"required,uuid"`
Name string `uri:"name" binding:"required"`
}
func main() {
route := gin.Default()
route.GET("/:name/:id", func(c *gin.Context) {
var person Person
if err := c.ShouldBindUri(&person); err != nil {
c.JSON(400, gin.H{"msg": err.Error()})
return
}
c.JSON(200, gin.H{"name": person.Name, "uuid": person.ID})
})
route.Run(":8088")
}
注意:/*name
格式的路径参数可以匹配/,/abc
,注意区分
获取GET请求参数
c.Query("lastname")
func main() {
router := gin.Default()
// 匹配的url格式: /welcome?firstname=Jane&lastname=Doe
router.GET("/welcome", func(c *gin.Context) {
firstname := c.DefaultQuery("firstname", "Guest")
lastname := c.Query("lastname") // 是 c.Request.URL.Query().Get("lastname") 的简写
c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
})
router.Run(":8080")
}
获取application/x-www-form-urlencoded参数
加入请求内容为:
POST /post?ids[a]=1234&ids[b]=hello HTTP/1.1
Content-Type: application/x-www-form-urlencoded
names[first]=thinkerou&names[second]=tianou
func main() {
router := gin.Default()
router.POST("/post", func(c *gin.Context) {
ids := c.QueryMap("ids")
names := c.PostFormMap("names")
fmt.Printf("ids: %v; names: %v", ids, names)
})
router.Run(":8080")
}
绑定URL
查询参数
ShouldBindQuery
函数只绑定 url 查询参数而忽略 post 数据。参阅详细信息.c.DefaultQuery
c.Query
type Person struct {
Name string `form:"name"`
Address string `form:"address"`
}
func main() {
route := gin.Default()
route.Any("/testing", startPage)
route.Run(":8085")
}
func startPage(c *gin.Context) {
var person Person
if c.ShouldBindQuery(&person) == nil {
log.Println("====== Only Bind By Query String ======")
log.Println(person.Name)
log.Println(person.Address)
}
c.String(200, "Success")
}
获取POST Body参数
ShouldBindJSON
content-type: application/json
注意:请求实体应当指定tag为json
func (OnlineMaController) DisassociationUser(c *gin.Context) {
request := req.DisassociationRequest{}
err := c.ShouldBindJSON(&request)
if err != nil || util.ObjectUtils.IsZeroValue(request) {
logrus.Warn("参数错误")
c.JSON(http.StatusOK, rest.FailureToUser())
return
}
if request.UserId <= 0 {
logrus.Warn("UserId not be negative")
c.JSON(http.StatusOK, rest.FailureToUser())
return
}
condition := bo.DisassociationUserBo{
UserId: request.UserId,
}
err = service.MaService{}.DisassociationUser(condition)
if err != nil {
c.JSON(http.StatusOK, rest.Failure("解除失败"))
return
}
c.JSON(http.StatusOK, rest.Success(nil))
}
传递数组参数
form
tag 指定数组格式colors[]
package main
import (
"github.com/gin-gonic/gin"
)
type myForm struct {
Colors []string `form:"colors[]"`
}
func main() {
r := gin.Default()
r.LoadHTMLGlob("views/*")
r.GET("/", indexHandler)
r.POST("/", formHandler)
r.Run(":8080")
}
func indexHandler(c *gin.Context) {
c.HTML(200, "form.html", nil)
}
func formHandler(c *gin.Context) {
var fakeForm myForm
c.Bind(&fakeForm)
c.JSON(200, gin.H{"color": fakeForm.Colors})
}