Multipart/Urlencoded binding
ShouldBind automatically detects the Content-Type and binds multipart/form-data or application/x-www-form-urlencoded request bodies into a struct. Use the form struct tag to map form field names to struct fields, and binding:"required" to enforce mandatory fields.
This is commonly used for login forms, registration pages, or any HTML form submission.
package main
import ( "net/http"
"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) { var form LoginForm // ShouldBind automatically selects the right binding based on Content-Type if err := c.ShouldBind(&form); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return }
if form.User == "user" && form.Password == "password" { c.JSON(http.StatusOK, gin.H{"status": "you are logged in"}) } else { c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"}) } })
router.Run(":8080")}Test it
# Multipart formcurl -X POST http://localhost:8080/login \ -F "user=user" -F "password=password"# Output: {"status":"you are logged in"}
# URL-encoded formcurl -X POST http://localhost:8080/login \ -d "user=user&password=password"# Output: {"status":"you are logged in"}
# Wrong credentialscurl -X POST http://localhost:8080/login \ -d "user=wrong&password=wrong"# Output: {"status":"unauthorized"}
# Missing required fieldcurl -X POST http://localhost:8080/login \ -d "user=user"# Output: {"error":"Key: 'LoginForm.Password' Error:Field validation for 'Password' failed on the 'required' tag"}