I want in init function to execute one of those two lines
func init() {
log.SetPrefix(">>>>>>>>>>>>> ")
log.SetOutput(ioutil.Discard)
}
How to achieve something similiar to C and macro definition in make file ? I build go program like go build my_project and I don't have any custom make file. Can I pass to build command flag and read inside code ?
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:
package main
func main() {
doThing()
}
// +build prod
package main
func doThing() {
println("I'm in prod mode")
}
// +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.