Multipart/Urlencoded binding

  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. }

Test it with:

  1. $ curl -v --form user=user --form password=password http://localhost:8080/login