Gin 使用示例(二十二):Multipart/Urlencoded 绑定和数据解析


我们可以像下面这样将表单请求数据绑定到指定结构体(默认通过 Multipart/Urlencoded 进行绑定):

package main
    
import (
    "github.com/gin-gonic/gin"
)
    
type LoginForm struct {
    User     string `form:"user" binding:"required"`
    Password string `form:"password" binding:"required"`
}
    
func main() {
    router := gin.Default()
    router.POST("/login", func(c *gin.Context) {
        // you can bind multipart form with explicit binding declaration:
        // c.ShouldBindWith(&form, binding.Form)
        // or you can simply use autobinding with ShouldBind method:
        var form LoginForm
        // in this case proper binding will be automatically selected
        if c.ShouldBind(&form) == nil {
            if form.User == "xueyuanjun" && form.Password == "123456" {
                c.JSON(200, gin.H{"status": "you are logged in"})
            } else {
                c.JSON(401, gin.H{"status": "unauthorized"})
            }
        }
    })
    router.Run(":8080")
}

启动服务器,在终端窗口通过 curl 发起请求:

-w823

此外还可以上下文对象 gin.Context 中直接解析表单请求数据:

func main() {
  router := gin.Default()

  router.POST("/form_post", func(c *gin.Context) {
    // 解析表单字段 message
    message := c.PostForm("message")
    // 解析表单字段 nick,如果为空的话使用默认值 xueyuanjun
    nick := c.DefaultPostForm("nick", "xueyuanjun")

    c.JSON(200, gin.H{
      "status":  "posted",
      "message": message,
      "nick":    nick,
    })
  })
  router.Run(":8080")
}

点赞 取消点赞 收藏 取消收藏

<< 上一篇: Gin 使用示例(二十一):模型绑定和验证

>> 下一篇: Gin 使用示例(二十三):渲染多个 HTML 模板