gin如何獲得前端的童鞋的參數(shù)呢
/*
@Author : 寒云
@Email : 1355081829@qq.com
@Time : 2019/10/15 11:51
*/
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.POST("/post", func(c *gin.Context) {
id := c.Query("id")
name := c.PostForm("name")
c.JSON(http.StatusOK, gin.H{"id": id, "name": name})
})
_ = r.Run(":8089")
}
用postman模擬請求

image.png
在這個例子中我們有g(shù)et參數(shù)和post參數(shù)
1、get參數(shù)
id := c.Query("id")
在這里我們獲得了地址http://127.0.0.1:8089/post?id=1中的id參數(shù)
2、post參數(shù)
name := c.PostForm("name")
在這里我們獲得了form表單中的post參數(shù)
3、get參數(shù)默認值
id := c.DefaultQuery("id", "0")
4、post參數(shù)默認值
name := c.DefaultPostForm("name", "hanyun")
5、GetQueryArray接收數(shù)組參數(shù)
r.GET("/array", func(c *gin.Context) {
if idList, err := c.GetQueryArray("idList"); err {
fmt.Println(err)
fmt.Println(idList[0])
c.JSON(http.StatusOK, gin.H{"dataList": idList})
} else {
c.JSON(http.StatusOK, gin.H{"dataList": []string{}})
}
})
我們的請求地址http://127.0.0.1:8089/array?idList=1&idList=2&idList=3,用postman模擬測試

image.png
6、QueryArray接收數(shù)組參數(shù)
r.GET("/QueryArray", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"dataList": c.QueryArray("idList")})
})
請求地址http://127.0.0.1:8089/QueryArray?idList=1&idList=2&idList=3我們得到的結(jié)果和GetQueryArray的數(shù)據(jù)一樣
7、QueryMap接收參數(shù)
r.POST("/QueryMap", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"dataList": c.QueryMap("idList")})
})
請求地址http://127.0.0.1:8089/QueryMap?idList[name]=hanyun&idList[password]=21212121,用postman模擬

image.png
8、PostFormMap接收參數(shù)
r.POST("/PostFormMap", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"dataList": c.PostFormMap("idList")})
})
請求地址http://127.0.0.1:8089/PostFormMap,用postman模擬測試

image.png
9、PostFormArray接收參數(shù)
r.POST("/PostFormArray", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"dataList": c.PostFormArray("idList")})
})
請求地址http://127.0.0.1:8089/PostFormArray,用postman模擬測試

image.png
10、Param獲得參數(shù)
r.GET("/param/:name", func(c *gin.Context) {
name := c.Param("name")
c.JSON(http.StatusOK, gin.H{"dataList": name})
})
請求地址http://127.0.0.1:8089/param/hanyun,用postman模擬請求

image.png