登录
首页 >  Golang >  Go问答

将值附加到 c.Json 响应

来源:stackoverflow

时间:2024-04-19 17:48:33 326浏览 收藏

学习Golang要努力,但是不要急!今天的这篇文章《将值附加到 c.Json 响应》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!

问题内容

我想将一个值附加到我的代码返回的响应中,这是我已经拥有的:

publishershare := 25 // i also have this variable that want to append to the returned response.
c.json(http.statusok, nf) // nf is a row found and returned from database.

这会返回这样的 json:

{
    "id": 105324,
    "title": "test title",
    "last_update": "2021-03-10t12:50:37+03:30",
    "created_at": "2021-03-10t12:50:36+03:30",
    "updated_at": "2021-05-05t05:46:39.352859604z"
}

我需要一个像这样的 json 结果:

{
    "id": 105324,
    "title": "test title",
    "last_update": "2021-03-10t12:50:37+03:30",
    "created_at": "2021-03-10t12:50:36+03:30",
    "updated_at": "2021-05-05t05:46:39.352859604z",
    "publisher_share": 25 // i want this to be added.
}

这是我到目前为止所尝试过的,但它改变了架构并且不再向后兼容:

c.Json(http.StatusOK, gin.H{"book": nf, "publisher_share": publisherShare})

但这不是我想要的json结果。我想要 publisher_share 以及其他字段,就像我上面提到的 json 结果一样。


正确答案


您可以将发布商共享添加到与以下相同的类型

type nfType struct {
    // All of the db row fields
    PublisherShare int `json:"publisher_share,omitempty" db:"-"`
}

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《将值附加到 c.Json 响应》文章吧,也可关注golang学习网公众号了解相关技术文章。

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