Create a string variable that you can test. Then set that string variable using -X
passed to the linker. For example:
package main
var MODE string
func main() {
if MODE == "PROD" {
println("I'm in prod mode")
} else {
println("I'm NOT in prod mode")
}
}
Now, if you build this with just go build
, MODE
will be ""
. But you can also build it this way:
go build -ldflags "-X main.MODE PROD"
And now MODE
will be "PROD"
. You can use that to modify your logic based on build settings. I generally use this technique to set version numbers in the binary; but it can be used for all kinds of build-time configuration. Note that it can only set strings. So you couldn't make MODE
a bool or integer.
You can also achieve this with tags, which are slightly more complicated to set up, but much more powerful. Create three files:
main.go
package main
func main() {
doThing()
}
main_prod.go
// +build prod
package main
func doThing() {
println("I'm in prod mode")
}
main_devel.go
// +build !prod
package main
func doThing() {
println("I'm NOT in prod mode")
}
Now when you build with go build
, you'll get your main_devel.go
version (the filename doesn't matter; just the // +build !prod
line at the top). But you can get a production build by building with go build -tags prod
.
See the section on Build Constraints in the build documentation.