绑定示例


Gin的参数绑定解析函一共两种类型:动态和固定类型

  1. //动态解析:根据http header头的Content-type 来自动选择解析类型
  2. func (c *Context) ShouldBind(obj interface{}) error {
  3. //todo
  4. }
  5. //固定解析类型:只能解析json传参形式
  6. func (c *Context) ShouldBindJSON(obj interface{}) error {
  7. //todo
  8. }
  9. ...

示例

  1. package main
  2. import (
  3. "github.com/gin-gonic/gin"
  4. )
  5. type LoginForm struct {
  6. User string `form:"user" binding:"required"`
  7. Password string `form:"password" binding:"required"`
  8. }
  9. func main() {
  10. router := gin.Default()
  11. router.POST("/login", func(c *gin.Context) {
  12. // you can bind multipart form with explicit binding declaration:
  13. // c.ShouldBindWith(&form, binding.Form)
  14. // or you can simply use autobinding with ShouldBind method:
  15. var form LoginForm
  16. // in this case proper binding will be automatically selected
  17. if c.ShouldBind(&form) == nil {
  18. if form.User == "user" && form.Password == "password" {
  19. c.JSON(200, gin.H{"status": "you are logged in"})
  20. } else {
  21. c.JSON(401, gin.H{"status": "unauthorized"})
  22. }
  23. }
  24. })
  25. router.Run(":8080")
  26. }

请求

  1. urlencod 默认参数形式
  1. $ curl -d 'user=uuu&password=pppp' http://yourhost.com/login
  1. json字符串形式
  1. $ curl -H 'Context-type:application/json' -d '{"user":"uuu", "password":"pppp"}' http://yourhost.com/login
  1. 当然还有其他很多形式,一下是gin所支持的绑定参数形式
  1. const (
  2. MIMEJSON = "application/json"
  3. MIMEHTML = "text/html"
  4. MIMEXML = "application/xml"
  5. MIMEXML2 = "text/xml"
  6. MIMEPlain = "text/plain"
  7. MIMEPOSTForm = "application/x-www-form-urlencoded"
  8. MIMEMultipartPOSTForm = "multipart/form-data"
  9. MIMEPROTOBUF = "application/x-protobuf"
  10. MIMEMSGPACK = "application/x-msgpack"
  11. MIMEMSGPACK2 = "application/msgpack"
  12. MIMEYAML = "application/x-yaml"
  13. )

结构体tag的用法

  1. 如果未定义tag, 请求参数字段必须和结构体定义的字段名称一致,否则解析失败
  2. 如果tag 定义,则必须是form:"字段名称" ,这样我们就可以,以定义的字段名称来进行传参了