1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
    7. <title>Document</title>
    8. </head>
    9. <body>
    10. <form action="http://localhost:8000/loginForm" method="post" enctype="application/x-www-form-urlencoded">
    11. 用户名<input type="text" name="username"><br>
    12. 密码<input type="password" name="password">
    13. <input type="submit" value="提交">
    14. </form>
    15. </body>
    16. </html>
    1. package main
    2. import (
    3. "net/http"
    4. "github.com/gin-gonic/gin"
    5. )
    6. // 定义接收数据的结构体
    7. type Login struct {
    8. // binding:"required"修饰的字段,若接收为空值,则报错,是必须字段
    9. User string `form:"username" json:"user" uri:"user" xml:"user" binding:"required"`
    10. Pssword string `form:"password" json:"password" uri:"password" xml:"password" binding:"required"`
    11. }
    12. func main() {
    13. // 1.创建路由
    14. // 默认使用了2个中间件Logger(), Recovery()
    15. r := gin.Default()
    16. // JSON绑定
    17. r.POST("/loginForm", func(c *gin.Context) {
    18. // 声明接收的变量
    19. var form Login
    20. // Bind()默认解析并绑定form格式
    21. // 根据请求头中content-type自动推断
    22. if err := c.Bind(&form); err != nil {
    23. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
    24. return
    25. }
    26. // 判断用户名密码是否正确
    27. if form.User != "root" || form.Pssword != "admin" {
    28. c.JSON(http.StatusBadRequest, gin.H{"status": "304"})
    29. return
    30. }
    31. c.JSON(http.StatusOK, gin.H{"status": "200"})
    32. })
    33. r.Run(":8000")
    34. }

    效果展示:
    表单数据解析和绑定 - 图1