You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go Gin框架嵌套结构体required绑定失效,如何使其生效?

Gin框架嵌套结构体required绑定失效问题解决

我在使用Gin框架绑定JSON请求体的嵌套结构体时遇到一个问题:嵌套结构体(如下方代码中的Nested)的required绑定规则不生效,但string、int这类普通类型的字段,哪怕是嵌套的,绑定都正常。

问题代码示例

package main

import (
    "fmt"

    "github.com/gin-gonic/gin"
)

type Nested struct {
    Hello string `json:"hello"`
}

type TransferCreateBody struct {
    TestNested    Nested `json:"nested" binding:"required"`
    TestNotNested string `json:"not_nested" binding:"required"`
}

func main() {
    g := gin.Default()
    g.POST("/hello", func(c *gin.Context) {
        var req TransferCreateBody
        if err := c.ShouldBindJSON(&req); err != nil {
            fmt.Println(err)
            c.JSON(400, gin.H{"error": err.Error()})
            return
        }
        c.JSON(200, gin.H{"hello": req.TestNested.Hello})
    })
    g.Run(":9000")
}

测试请求

curl -X POST http://localhost:9000/hello \
   -H "Content-Type: application/json" \
   -d '{"not_nested": "test"}'

解决方法

问题出在值类型的嵌套结构体上:Gin会自动初始化值类型的嵌套结构体为零值,这会让required校验误以为字段已经存在,不会触发错误。

只需要把嵌套结构体的类型改成指针类型,当请求中没有该字段时,指针会保持nil状态,required校验就能正常生效:

package main

import (
    "fmt"

    "github.com/gin-gonic/gin"
)

type Nested struct {
    Hello string `json:"hello"`
}

type TransferCreateBody struct {
    // 将Nested改为*Nested指针类型
    TestNested    *Nested `json:"nested" binding:"required"`
    TestNotNested string `json:"not_nested" binding:"required"`
}

func main() {
    g := gin.Default()
    g.POST("/hello", func(c *gin.Context) {
        var req TransferCreateBody
        if err := c.ShouldBindJSON(&req); err != nil {
            fmt.Println(err)
            c.JSON(400, gin.H{"error": err.Error()})
            return
        }
        c.JSON(200, gin.H{"hello": req.TestNested.Hello})
    })
    g.Run(":9000")
}

再次发送原测试请求,Gin会返回错误提示:Key: 'TransferCreateBody.TestNested' Error:Field validation for 'TestNested' failed on the 'required' tag,说明required绑定已经生效。

内容的提问来源于stack exchange,提问作者Pascal Delange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 17:27:19