gin參數(shù)獲取

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容