GoSuda

Compile-Time Variable Injection in Go

By wHoIsDReAmer
views ...

Background

While working on a company project recently, I sought methods to inject variables at compile time without utilizing .env files. I hypothesized that this approach would offer substantial convenience, as it would necessitate only a single file rather than .env or multiple configuration files.

Initially, I investigated go:generate CLI tools that could generate constant files from .env files, but none were found.

However, if that were the case, it would be simpler to directly modify the constants rather than undergoing the cumbersome generation process. Consequently, I sought a method to inject values at compile time, similar to Rust's include_bytes! macro.

Compile-Time Variable Injection

The usage is straightforward.

1package main
2
3import "fmt"
4
5var Foo string
6
7func main() {
8    fmt.Println(Foo)
9}

Given the aforementioned code, values can be injected during the build process as follows:

1go build -ldflags="-X 'main.Foo=bar'"

By passing arguments via ldflag, the value bar is injected into the Foo variable at compile time during the build. This is simple.

If multiple packages or variables with the same name exist within a project, specifying the package path is required.

1// github.com/myproject/config/config.go
2package config
3
4var Version string
5
6// github.com/myproject/internal/config/config.go  
7package config
8
9var BuildTime string

In such cases, injection can be differentiated as follows:

1go build -ldflags="-X 'github.com/myproject/config.Version=v1.0.0' -X 'github.com/myproject/internal/config.BuildTime=2025-05-27'"

Even when multiple variables reside within the same package, additional arguments can simply be provided.

1go build -ldflags="-X 'main.Version=v1.0.0' -X 'main.BuildTime=2025-05-27' -X 'main.GitCommit=abc123'"

The characteristics are as follows:

  • Variables need not be public: Variables commencing with a lowercase letter can also be injected.
  • Only string types are supported: Other data types are not supported.

Reference