Gin传参和接收参数的方式

Gin查询参数和接收参数的方式

常用 Gin 绑定方法对比

方法 用途 特点
c.Bind() 自动识别 Content-Type 最通用,根据请求头自动选择绑定方式
c.ShouldBindJSON() 只绑定 JSON 强制使用 JSON 格式,类型明确
c.ShouldBindXML() 只绑定 XML 强制使用 XML 格式
c.ShouldBindQuery() 只绑定查询参数 适用于 GET 请求的 URL 参数解析
c.ShouldBindUri() 绑定 URI 参数 解析路径参数(如 /user/:id
c.ShouldBindForm() 只绑定表单数据 专用于 form-data/x-www-form-urlencoded

1、request body 绑定------ShouldBindJSON

go 复制代码
// CreateUserRequest 创建用户请求参数
type CreateUserRequest struct {
	Phone    string     `json:"phone" binding:"required"`
	Email    string     `json:"email" binding:"required,email"`
	Nickname string     `json:"nickname"`
	RealName string     `json:"realname"`
	Gender   string     `json:"gender" binding:"oneof=男 女"`
	Birth    *time.Time `json:"birth"`
}

func CreateUser(c *gin.Context) {
	// 定义接收参数的结构体
	var reqUser CreateUserRequest
	// 绑定并验证请求body参数
	if err := c.ShouldBindJSON(&reqUser); err != nil {
		 c.JSON(http.StatusBadRequest, gin.H{
		 	"status":     "error",
		 	"message123": "请求参数错误",
		 })
		return
	}
	// 创建用户实体
	user := repository.User{
		Phone:    reqUser.Phone,
		Email:    reqUser.Email,
		Nickname: reqUser.Nickname,
		RealName: reqUser.RealName,
		Gender:   reqUser.Gender,
		// 其他字段...
	}
	// 保存到数据库
	db := repository.GetDB()
	if err := db.Create(&user).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"status":  "error",
			"message": "创建用户失败: " + err.Error(),
		})
		return
	}

	// 返回成功响应
	c.JSON(http.StatusCreated, gin.H{
		"status":  "success",
		"message": "用户创建成功",
		"id":      user.ID,
	})

2、路由参数

go 复制代码
func main() {
  router := gin.Default()

  // 此 handler 将匹配 /user/john 但不会匹配 /user/ 或者 /user
  router.GET("/user/:name", func(c *gin.Context) {
    name := c.Param("name")
    c.String(http.StatusOK, "Hello %s", name)
  })

  // 此 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)
  })

  router.Run(":8080")
}

3、Query和post form

请求内容:

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")
}

结果:

id: 1234; page: 1; name: manu; message: this_is_great