Skip to content

请求参数

JSON

go
type CreateAppRequest struct {
	Name   string `json:"name"`
	AppID  int    `json:"app_id"`
	Enable bool   `json:"enable"`
}

func CreateApp(c *gin.Context) {
	var req CreateAppRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	// 使用 req.Name, req.AppID, req.Enable
	c.JSON(http.StatusOK, gin.H{"name": req.Name})
}

Query 与 PostForm

https://gin-gonic.com/zh-cn/docs/examples/query-and-post-form/

sh
POST /post?id=1234&page=1 HTTP/1.1
Content-Type: application/x-www-form-urlencoded

name=manu&message=this_is_great
go
func main() {
  router := gin.Default()

  router.POST("/post", func(c *gin.Context) {

    id := c.Query("id")
    page := c.DefaultQuery("page", "0")
    name := c.PostForm("name")
    message := c.PostForm("message")

    fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)
  })
  router.Run(":8080")
}

路由参数

go
  // 此 handler 将匹配 /user/john 但不会匹配 /user/ 或者 /user
  router.GET("/user/:name", func(c *gin.Context) {
    name := c.Param("name")
    c.String(http.StatusOK, "Hello %s", name)
  })
go
  // 此 handler 将匹配 /user/john/ 和 /user/john/send
  // 如果没有其他路由匹配 /user/john,它将重定向到 /user/john/
  router.GET("/user/:name/*action", func(c *gin.Context) {
    name := c.Param("name")
    action := c.Param("action")
    message := name + " is " + action
    c.String(http.StatusOK, message)
  })