1. 表单参数

  • 表单传输为post请求,http常见的传输格式为四种:
    • application/json
    • application/x-www-form-urlencoded
    • application/xml
    • multipart/form-data
  • 表单参数可以通过PostForm()方法获取,该方法默认解析的是x-www-form-urlencoded或from-data格式的参数
  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:8080/form" method="post" action="application/x-www-form-urlencoded">
  11. 用户名:<input type="text" name="username" placeholder="请输入你的用户名"> <br>
  12. &nbsp;&nbsp;&nbsp;码:<input type="password" name="userpassword" placeholder="请输入你的密码"> <br>
  13. <input type="submit" value="提交">
  14. </form>
  15. </body>
  16. </html>
  1. package main
  2. //
  3. import (
  4. "fmt"
  5. "net/http"
  6. "github.com/gin-gonic/gin"
  7. )
  8. func main() {
  9. r := gin.Default()
  10. r.POST("/form", func(c *gin.Context) {
  11. types := c.DefaultPostForm("type", "post")
  12. username := c.PostForm("username")
  13. password := c.PostForm("userpassword")
  14. // c.String(http.StatusOK, fmt.Sprintf("username:%s,password:%s,type:%s", username, password, types))
  15. c.String(http.StatusOK, fmt.Sprintf("username:%s,password:%s,type:%s", username, password, types))
  16. })
  17. r.Run()
  18. }

输出结果:

表单参数 - 图1

表单参数 - 图2