Changing a server port or a counter’s increment should not require editing code and rebuilding. An environment variable supplies a named value from the user’s session when the application starts. For example, `INC=2 go run counter.go` changes the counter’s step; an invalid value falls back to one. section 8.1
Listing 8.5 core.go
package config
import "os"
...
// LoadFromEnv will load configuration solely from the environment
func (c *Configuration) LoadFromEnv() {
if lang := os.Getenv("DEFAULT_LANGUAGE"); lang != "" { #1
c.DefaultLanguage = lang
}
if port := os.Getenv("PORT"); port != "" {
c.Port = port
}
}
A Go configuration method reads `DEFAULT_LANGUAGE` and `PORT` with `os.Getenv`. It replaces the existing value only when the environment value is nonempty, leaving defaults in place otherwise. section 8.2.1
Configuration can be layered: start with defaults, load a JSON file, apply environment variables, then apply command-line flags. Later values override earlier ones. Validate values before using them: a port helper adds a missing colon and falls back to the default if the port number is invalid. section 8.2.3 section 8.2.1
PORT=8081 go run cmd/main.go --config_file config.json 2022/03/31 14:21:59 loading configuration from file: config.json 2022/03/31 14:21:59 listening on :8081
Run the API with `PORT=8081` and a JSON configuration file to see the environment value override the file’s port of 8079. A `--port` flag can override both. section 8.3.1 section 8.2.3
Use session-wide `export` when several commands need the same value, or prepend a value for one command. The same configuration approach can select an external client when its endpoint is set. In Kubernetes, secrets and configuration files can populate environment variables. The operational payoff is changing deployed behavior without changing application code. section 8.2.3 section 8.3.2 section 10.8


















