登录
首页 >  Golang >  Go问答

如何在 Golang 中拥有具有相同成员但不同 JSON 标签的开发结构和生产结构?

来源:stackoverflow

时间:2024-04-21 19:45:34 309浏览 收藏

学习Golang要努力,但是不要急!今天的这篇文章《如何在 Golang 中拥有具有相同成员但不同 JSON 标签的开发结构和生产结构?》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!

问题内容

第一次提问! 我正在尝试将使用相同结构的开发和生产分开。

我正在使用 airtable,它将记录作为 json 发送,并带有我们在解组时使用的 fld 标签。

type airtablerecord struct {
    name   *string  `json:"fldaaaa,omitempty"`
}

我有 2 个独立的 airtable:

  1. 用于开发
  2. 用于生产

它们是相同的,只是由于 airtable 的工作方式,字段被赋予了不同的 fld 标签

我的 airtable 场地的图片

现在要将开发环境与生产环境分开,我必须根据我指向的 airtable 取消注释正确的成员。

type airtablerecord struct {
    // development
    name   *string  `json:"fldaaaa,omitempty"`

    // production
    //name   *string  `json:"fldbbbb,omitempty"`
}

我将此类型保留在它自己的 model.go 文件中,供其他包使用。

我调查过:

  • 一行中有多个 json 标签,golang 不会这样做
type airtablerecord struct {
    // development or production
    name   *string  `json:"fldaaaa,fldbbbb,omitempty"`
}
  • 使用构建标签分隔我的文件,也许这可行,但我做错了

文件1:

// +build dev
type airtablerecord struct {
    // development
    name   *string  `json:"fldaaaa,omitempty"`
}

文件2:

type AirtableRecord struct {
    // Production
    Name   *string  `json:"fldBBBB,omitempty"`
}
  • 研究过使用重新标记,但他们给出的示例看起来不像我正在寻找的
    • 重新标记链接:https://pkg.go.dev/github.com/sevlyar/[电子邮件受保护]

我想根据我是在开发模式还是生产模式下运行来动态更改此成员的标签。

任何及所有帮助将不胜感激!


正确答案


如果您在此块中收到 redeclared 使用构建标记的 编译错误,请在 prod 文件上指定一个未标记的标记,以避免出现这种情况。

开发文件

// +build dev
type airtablerecord struct {
    // development
    name   *string  `json:"fldaaaa,omitempty"`
}

产品文件

// +build !dev
type airtablerecord struct {
    // development
    name   *string  `json:"fldaaaa,omitempty"`
}

构建

# for dev
go build -tags=dev -o devrel
# for prod
go build -tags=prod -o prodrel  
or no tags for prod

自 1.17 以来,构建标签格式也发生了变化,所以在您的情况下,它会是,

//go:build dev

但也应该与旧的一起使用。

终于介绍完啦!小伙伴们,这篇关于《如何在 Golang 中拥有具有相同成员但不同 JSON 标签的开发结构和生产结构?》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

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