Multipart/Urlencoded 绑定

  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. // 你可以使用显式绑定声明绑定 multipart form:
  13. // c.ShouldBindWith(&form, binding.Form)
  14. // 或者简单地使用 ShouldBind 方法自动绑定:
  15. var form LoginForm
  16. // 在这种情况下,将自动选择合适的绑定
  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. $ curl -v --form user=user --form password=password http://localhost:8080/login