When a service must run differently across environments, a command-line argument lets an operator supply a value or change execution settings without editing or rebuilding code. A flag such as --port 8082 can override configuration loaded from defaults, a file, or environment variables. section 8.2.3 section 8.3.1
A practical configuration flow layers command-line arguments with other sources:
- Start with default configuration, such as port :8080. section 8.2
- Optionally load a JSON configuration file through a file path argument. section 8.2.2
- Apply environment variables, then let explicit flags take precedence over earlier values. section 8.2.3
- Parse the arguments before starting the service and pass the resulting configuration to application code. section 8.2.3 section 8.3.1
Overriding a service port
A JSON file sets port 8079. Running `go run cmd/main.go --config_file config.json` starts the service on :8079. An environment variable changes it to :8081, while `--port 8082` overrides both sources and starts the service on :8082. section 8.3.1
Listing 8.8 core.go
import (
"encoding/json"
"errors"
"flag"
"io/ioutil"
"log"
"os"
"strconv"
)
...
//LoadConfiguration will provide cycle through flags, files, and finally env variables to load configuration.
func LoadConfiguration() Configuration {
cfgfileFlag := flag.String("config_file", "", "load configurations from
a file") #1
portFlag := flag.String("port", "", "set port")
flag.Parse() #2
cfg := defaultConfiguration
if cfgfileFlag != nil && *cfgfileFlag != "" { #3
if err := cfg.LoadFromJSON(*cfgfileFlag); err != nil {
log.Printf("unable to load configuration from json: %s, using
default values", *cfgfileFlag)
}
}
cfg.LoadFromEnv() #4
if portFlag != nil && *portFlag != "" { #5
cfg.Port = *portFlag
}
cfg.ParsePort() #6
return cfg
}
The Go implementation declares configuration flags, calls flag.Parse, loads defaults and optional files, then applies environment variables and explicit flag values. section 8.2.3













