Gin请求动态url-context.Param

  • 定义path:path:/admin/:xxx
  • 获取参数c.Param("xxx")
  1. package main
  2. import (
  3. "net/http"
  4. "github.com/gin-gonic/gin"
  5. )
  6. func main() {
  7. r := gin.Default()
  8. r.GET("/back/:name/:action/to", func(c *gin.Context) {
  9. name := c.Param("name")
  10. action := c.Param("action")
  11. c.JSON(http.StatusOK, gin.H{
  12. "name": name,
  13. "action": action,
  14. })
  15. })
  16. r.Run(":8888")
  17. }
  1. => curl 127.0.0.1:8888/back/cunwang/add/to
  2. <= {"action":"add","name":"cunwang"}%

Gin请求动态url-context.ShoudBindUri

ShoudBindUri可以让我们对动态参数进行一些定义约束

通过接收一个结构体实例的指针,结构体定义的时候通过tag做一些字段约束,那么就可以达到传值约束的效果

  1. package main
  2. import (
  3. "net/http"
  4. "github.com/gin-gonic/gin"
  5. )
  6. type IdAction struct {
  7. Id string `uri:"id" binding:"required,uuid"` //其实这个required在uri做不到什么校验,不传直接404了~
  8. Action string `uri:"action" binding:"required"`
  9. }
  10. func main() {
  11. r := gin.Default()
  12. r.GET("/back/:id/:action", func(c *gin.Context) {
  13. var idAction IdAction
  14. err := c.ShouldBindUri(&idAction)
  15. if err != nil {
  16. c.JSON(http.StatusBadRequest, gin.H{
  17. "err": err.Error(),
  18. })
  19. return
  20. }
  21. c.JSON(http.StatusOK, gin.H{
  22. "id": idAction.Id,
  23. "action": idAction.Action,
  24. })
  25. })
  26. r.Run(":8888")
  27. }
  1. # 校验通过
  2. ~ curl 127.0.0.1:8888/back/8cb82a68-bde5-7029-ad39-917f684ffb07/addclea
  3. {"action":"addclea","name":"8cb82a68-bde5-7029-ad39-917f684ffb07"}%
  4. # 校验不通过
  5. ~ curl 127.0.0.1:8888/back/11111122/add
  6. {"err":"Key: 'NameAction.Name' Error:Field validation for 'Name' failed on the 'uuid' tag"}%

Gin 获取Get请求参数 context.Query

  1. r.GET("/back", func(c *gin.Context) {
  2. id := c.Query("id")
  3. action := c.Query("action")
  4. c.JSON(http.StatusOK, gin.H{
  5. "id": id,
  6. "action": action,
  7. })
  8. })
  1. ~ curl 127.0.0.1:8888/back?id=1&action=add
  2. {"action": "add","id": "1"}

Gin 获取Get请求参数的默认值context.DefaultQuery

  1. r.GET("/back", func(c *gin.Context) {
  2. id := c.DefaultQuery("id", "1")
  3. action := c.DefaultQuery("action", "add")
  4. c.JSON(http.StatusOK, gin.H{
  5. "id": id,
  6. "action": action,
  7. })
  8. })
  1. # 无参数携带,使用默认值
  2. ~ curl http://127.0.0.1:8888/back
  3. {"action":"add","id":"1"}%
  4. # 有参数携带 使用参数值
  5. ~ curl http://127.0.0.1:8888/back\?id\=2\&action\=delete
  6. {"action":"delete","id":"2"}%

Gin 获取Get请求参数context.ShouldBind

c.ShouldBind,配合 form tag 可以完成 Get的表单验证

  1. type IdAction struct {
  2. Id string `form:"id" binding:"required,uuid"`
  3. Action string `form:"action" binding:"required"`
  4. }
  1. r.GET("/getShouldBind", func(c *gin.Context) {
  2. var idAction IdAction
  3. err := c.ShouldBind(&idAction)
  4. if err != nil {
  5. c.JSON(http.StatusOK, gin.H{
  6. "err": err.Error(),
  7. })
  8. return
  9. }
  10. c.JSON(http.StatusOK, gin.H{
  11. "id": idAction.Id,
  12. "action": idAction.Action,
  13. })
  14. })
  1. # 校验失败!
  2. ~ curl http://127.0.0.1:8888/getShouldBind\?id\=1\&action\=delete
  3. {"err":"Key: 'IdAction.Id' Error:Field validation for 'Id' failed on the 'uuid' tag"}%
  4. # 校验成功!
  5. ~ curl http://127.0.0.1:8888/getShouldBind\?id\=8cb82a68-bde5-7029-ad39-917f684ffb07\&action\=delete
  6. {"action":"delete","id":"8cb82a68-bde5-7029-ad39-917f684ffb07"}%

Get使用**shouldBind**可以接受拼接到**url****Params**参数,也可以接受 **contentType: form-data**的参数

  1. r.GET("/getShouldBind", func(c *gin.Context) {
  2. var idAction IdAction
  3. // id := c.DefaultQuery("id", "1")
  4. // action := c.DefaultQuery("action", "add")
  5. err := c.ShouldBind(&idAction)
  6. if err != nil {
  7. c.JSON(http.StatusOK, gin.H{
  8. "err": err.Error(),
  9. "content-type": c.Request.Header["Content-Type"],
  10. })
  11. return
  12. }
  13. c.JSON(http.StatusOK, gin.H{
  14. "id": idAction.Id,
  15. "action": idAction.Action,
  16. "content-type": c.Request.Header,
  17. })
  18. })
# form-data
curl --location --request GET 'http://localhost:8888/getShouldBind' --form 'id="8cb82a68-bde5-7029-ad39-917f684ffb07"' --form 'action="add"'
{"action":"add","content-type":["multipart/form-data; boundary=------------------------0f2bd960b85dda6b"],"id":"8cb82a68-bde5-7029-ad39-917f684ffb07"}%

# params拼接url
curl --location --request GET 'http://localhost:8888/getShouldBind?id=8cb82a68-bde5-7029-ad39-917f684ffb07&action=add'
{"action":"add","content-type":null,"id":"8cb82a68-bde5-7029-ad39-917f684ffb07"}%

Gin 获取Post请求参数 context.PostForm

r.POST("/post", func(c *gin.Context) {
    id := c.PostForm("id")
    action := c.PostForm("action")
    c.JSON(http.StatusOK, gin.H{
        "id":     id,
        "action": action,
    })
})
 ~  curl http://127.0.0.1:8888/post -d id=2 -d action=delete
{"action":"delete","id":"2"}%

Gin 获取Post请求参数的默认值context.DefaultPostForm

r.POST("/post", func(c *gin.Context) {
    id := c.DefaultPostForm("id", "1")
    action := c.DefaultPostForm("action", "add")
    c.JSON(http.StatusOK, gin.H{
        "id":     id,
        "action": action,
    })
})
# 参数完整 使用参数值
~ curl http://127.0.0.1:8888/post -d id=2 -d action=update
{"action":"update","id":"2"}%

# 无参数 使用默认值 缺少action
~  curl http://127.0.0.1:8888/post -d id=1
{"action":"add","id":"1"}%

Gin 获取Post请求参数context.ShouldBind

c.ShouldBind,配合 form tag 可以完成 Post的表单验证

r.POST("/postShouldBind", func(c *gin.Context) {
    var idAction IdAction
    err := c.ShouldBind(&idAction)
    if err != nil {
        c.JSON(http.StatusOK, gin.H{
            "err": err.Error(),
        })
        return
    }
    c.JSON(http.StatusOK, gin.H{
        "id":     idAction.Id,
        "action": idAction.Action,
    })
})
# post shouldBind校验不通过
~  curl http://127.0.0.1:8888/postShouldBind -d id=1 -d action=add
{"err":"Key: 'IdAction.Id' Error:Field validation for 'Id' failed on the 'uuid' tag"}%

# post shouldBind校验通过
~  curl http://127.0.0.1:8888/postShouldBind -d id=8cb82a68-bde5-7029-ad39-917f684ffb07 -d action=add
  {"action":"add","id":"8cb82a68-bde5-7029-ad39-917f684ffb07"}%

Post请求使用shouldBind 可以接收ContentType为以下类型的

  • Content-Type: application/json
  • Content-Type: application/x-www-form-urlencoded
  • form-data
curl --location --request POST 'http://localhost:8888/postShouldBind' \
--header 'Content-Type: application/json' \
--data-raw '{
    "id":"8cb82a68-bde5-7029-ad39-917f684ffb07",
    "action":"add"
}'

{"action":"add","content-type":["application/json"],"id":"8cb82a68-bde5-7029-ad39-917f684ffb07"}%
curl --location --request POST 'http://localhost:8888/postShouldBind' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'id=8cb82a68-bde5-7029-ad39-917f684ffb07' \
--data-urlencode 'action=add'

{"action":"add","content-type":["application/x-www-form-urlencoded"],"id":"8cb82a68-bde5-7029-ad39-917f684ffb07"}%
curl --location --request POST 'http://localhost:8888/postShouldBind' \
--form 'id="8cb82a68-bde5-7029-ad39-917f684ffb07"' \
--form 'action="add"'

{"action":"add","content-type":["multipart/form-data; boundary=------------------------32f115dc003b4c6c"],"id":"8cb82a68-bde5-7029-ad39-917f684ffb07"}%

Gin 获取Post请求参数context.ShouldBindJSON

这个其实和上面的用法差不多,只不过ta只能接收Content-Typeapplication/json类型的数据

r.POST("/postShouldBindJson", func(c *gin.Context) {
    fmt.Print(c.Request.Header)
    var idAction IdAction
    err := c.ShouldBindJSON(&idAction)
    if err != nil {
        c.JSON(http.StatusOK, gin.H{
            "err":          err.Error(),
            "content-type": c.Request.Header["Content-Type"],
        })
        return
    }
    c.JSON(http.StatusOK, gin.H{
        "id":           idAction.Id,
        "action":       idAction.Action,
        "content-type": c.Request.Header["Content-Type"],
    })
})
  • Content-Type: application/x-www-form-urlencoded 无法解析
    ```bash curl —location —request POST ‘http://localhost:8888/postShouldBindJson‘ \ —header ‘Content-Type: application/x-www-form-urlencoded’ \ —data-urlencode ‘id=8cb82a68-bde5-7029-ad39-917f684ffb07’ \ —data-urlencode ‘action=add’

{“content-type”:[“application/x-www-form-urlencoded”],”err”:”invalid character ‘i’ looking for beginning of value”}%


-  `form-data` 无法解析  
```bash
curl --location --request POST 'http://localhost:8888/postShouldBindJson' \
--form 'id="8cb82a68-bde5-7029-ad39-917f684ffb07"' \
--form 'action="add"'

{"content-type":["multipart/form-data; boundary=------------------------a596ddaeeaf65568"],"err":"invalid character '-' in numeric literal"}%
  • Content-Type: application/json 可以解析
    ```bash curl —location —request POST ‘http://localhost:8888/postShouldBindJson‘ \ —header ‘Content-Type: application/json’ \ —data-raw ‘{ “id”:”8cb82a68-bde5-7029-ad39-917f684ffb07”, “action”:”add” }’

{“action”:”add”,”content-type”:[“application/json”],”id”:”8cb82a68-bde5-7029-ad39-917f684ffb07”}% ```

其实不同的请求方式,获取参数的方式都差不多更多,还说慢慢使用积累