将标签应用于每个结构体中的每个字段。

huangapple go评论79阅读模式
英文:

Apply tag to every field in every struct

问题

是否可以在每个结构体/多个结构体上应用默认的字段标签,而无需手动输入,并且保持代码更清晰?

例如:当我需要默认情况下将omitempty应用于每个结构体时

type SomeStruct struct {
    FieldOne string `json:"field_one,omitempty"`
    FieldTwo string `json:"field_two,omitempty"`
    FieldThree string `json:"field_three,omitempty"`
}

编写用于解析所有JSON响应并删除空字段的API中间件似乎非常耗费资源。

英文:

Is it possible to apply a default struct field tag to every struct / many structs without having to type it out, and also keeps code cleaner.

Eg: when i need omitempty to be applied by default to every struct

type SomeStruct struct {
    FieldOne string `json:"field_one,omitempty"`
    FieldTwo string `json:"field_two,omitempty"`
    FieldThree string `json:"field_three,omitempty"`
}

Writing middleware for my API to parse all JSON responses, then remove empty fields seems very expensive.

答案1

得分: 0

gomodifytags是一个用于修改/更新结构体字段标签的Go工具。它使得更新、添加或删除结构体字段标签变得非常简单。你可以轻松地添加新的标签,更新现有的标签(比如追加一个新的键,比如db、xml等),或者删除现有的标签。它还允许你添加和删除标签选项。它支持atom、vscode、vim-go和acme。

> https://github.com/fatih/gomodifytags

英文:

Go tool to modify/update field tags in structs. gomodifytags makes it easy to update, add or delete the tags in a struct field. You can easily add new tags, update existing tags (such as appending a new key, i.e: db, xml, etc..) or remove existing tags. It also allows you to add and remove tag options. It supports atom,vscode,vim-go,acme.

> https://github.com/fatih/gomodifytags

huangapple
  • 本文由 发表于 2022年1月25日 01:20:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/70837881.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定