Home > Net >  How to have a Development struct and Production struct in Golang with identical members but differen
How to have a Development struct and Production struct in Golang with identical members but differen

Time:12-02

First time asking a question! I am trying to separate my development and production that use the same struct.


I am working with Airtable, which sends records as a JSON with an fld tag that we use when unmarshaling.

type AirtableRecord struct {
    Name   *string  `json:"fldAAAA,omitempty"`
}

I have 2 separate Airtables:

  1. For development
  2. For production

They are identical, except because of how Airtable works the fields are given different fld tags

Image of my Airtable Field


Right now to separate development env from production env, I have to uncomment the right members depending which Airtable I am 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, that other packages use.

I have looked into:

  • Having multiple JSON tags in a line, Golang doesn't do this
type AirtableRecord struct {
    // Development or Production
    Name   *string  `json:"fldAAAA,fldBBBB,omitempty"`
}
  • Separating my files using build tags, maybe this works but I'm doing it wrong

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 change this Member's tag dynamically based on if I'm running in development mode or production mode.

Any and all help would be appreciated!

CodePudding user response:

If you are getting redeclared in this block compile error with build tags, then specify a not'ed tag on prod file, to avoid it.

Dev File

//  build dev
type AirtableRecord struct {
    // Development
    Name   *string  `json:"fldAAAA,omitempty"`
}

Prod File

//  build !dev
type AirtableRecord struct {
    // Development
    Name   *string  `json:"fldAAAA,omitempty"`
}

build with

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

Also build tag format has changed since 1.17 so in your case it will be,

//go:build dev

but should work with old one too.

  • Related