Home > Article > Backend Development > How to have development struct and production struct in Golang with same members but different JSON tags?
php Editor Apple In Golang development, we often encounter situations where we need to use the same members in the development structure and production structure, but need different JSON tags. In this case, we need to find a flexible solution so that we can easily switch between different tabs while writing code. This article will introduce how to implement this requirement in Golang to make the development process more efficient and flexible.
First time asking! I'm trying to separate development and production using the same structure.
I'm using airtable which sends the records as json with the fld tags we use when unmarshalling.
type airtablerecord struct { name *string `json:"fldaaaa,omitempty"` }
I have 2 separate airtables:
They are the same, it's just that due to the way airtable works, the fields are given different fld tags
Pictures of my airtable venue
Now to separate the development environment from the production environment, I have to uncomment the correct members based on the airtable I'm pointing to.
type airtablerecord struct { // development name *string `json:"fldaaaa,omitempty"` // production //name *string `json:"fldbbbb,omitempty"` }
I keep this type in it's own model.go file for use by other packages.
I have investigated:
type airtablerecord struct { // development or production name *string `json:"fldaaaa,fldbbbb,omitempty"` }
File 1:
// +build dev type airtablerecord struct { // development name *string `json:"fldaaaa,omitempty"` }
File 2:
type AirtableRecord struct { // Production Name *string `json:"fldBBBB,omitempty"` }
I want to dynamically change the label of this member based on whether I'm running in development mode or production mode.
Any and all help would be greatly appreciated!
If you receive a redeclared
compilation error using build flags in this block, specify an unmarked flag on the prod file , to avoid this situation.
Development files
// +build dev type airtablerecord struct { // development name *string `json:"fldaaaa,omitempty"` }
Product Documents
// +build !dev type airtablerecord struct { // development name *string `json:"fldaaaa,omitempty"` }
Construct
# for dev go build -tags=dev -o devrel # for prod go build -tags=prod -o prodrel or no tags for prod
The build tag format has also changed since 1.17, so in your case it would be,
//go:build dev
But should also be used with the old one.
The above is the detailed content of How to have development struct and production struct in Golang with same members but different JSON tags?. For more information, please follow other related articles on the PHP Chinese website!