登录
首页 >  Golang >  Go问答

是否有可能消失 gin-gonic 绑定 json 中的范围?

来源:stackoverflow

时间:2024-04-18 18:45:32 257浏览 收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《是否有可能消失 gin-gonic 绑定 json 中的范围?》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

问题内容

我正在用 gin-gonic 编写一个 api 服务器。

我遇到了与编组 json 相关的麻烦。

例如,我有一个如下所示的结构。

type foo struct {
    value     float32 `json:"value"`
    injection interface{}
}

我在运行时写下了一些字段并发送响应。

r.get("/ping", func(c *gin.context) {

    var foo = &foo{
        value: 19.8,
        injection: map[string]interface{}{
            "unit": "c",
            "constraints": map[string]interface{}{
                "min": 18,
                "max": 30,
            },
        },
    }

    c.json(200, foo)
})

结果,我可以看到这个 json 响应。

{
    "value": 19.8,
    "injection": {
        "constraints": {
            "max": 30,
            "min": 18
        },
        "unit": "c"
    }
}

但是如果我想得到下面的点赞,我该怎么办?

{
    "value": 19.8,
    "constraints": {
        "max": 30,
        "min": 18
    },
    "unit": "C"
}

我尝试在运行时分配所有字段,第一次工作正常,但添加很多很多字段后我遇到了地狱之门。

所以我可以说这与react中的标签类似。

ps。抱歉,我不确定标题是否符合我的意思。


解决方案


您可以直接使用地图来代替 foo

r.get("/ping", func(c *gin.context) {
    var data = map[string]interface{}{
        "value": 19.8,
        "unit":  "c",
        "constraints": map[string]interface{}{
            "min": 18,
            "max": 30,
        },
    }

    c.json(200, data)
})

如果您需要更通用的东西,您可以让 foo 实现 json.marshaler 接口,并让实现分别封送两个值,然后手动“合并”结果。

type Foo struct {
    Value     float32     `json:"value"`
    Injection interface{} `json:"-"`
}

func (f *Foo) MarshalJSON() ([]byte, error) {
    type tmp Foo
    out1, err := json.Marshal((*tmp)(f))
    if err != nil {
        return nil, err
    }
    out2, err := json.Marshal(f.Injection)
    if err != nil {
        return nil, err
    }

    out1[len(out1)-1] = ','           // replace the '}' at the end with ','
    out2 = out2[1:]                   // drop the leading '{'
    return append(out1, out2...), nil // merge
}

请注意,上面假设 injection 持有一个将被编组到 json 对象 中的值,如果该值是标量或切片类型,则需要以不同的方式处理这些情况。

https://play.golang.com/p/kYIu6HnqVIp

到这里,我们也就讲完了《是否有可能消失 gin-gonic 绑定 json 中的范围?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>