Load configuration and validate inputs
Load configuration and validate inputs
Choose explicit precedence: built-in default, JSON file, environment, then flags. The last supplied layer wins. Pass file bytes and a lookup function so tests do not depend on the machine environment.
package main
import ( "encoding/json" "errors" "flag" "fmt" "io" "strconv")
func config(file []byte, lookup func(string) (string, bool), args []string) (int, error) { c := struct { Limit int `json:"limit"` }{10} if len(file) > 0 { if err := json.Unmarshal(file, &c); err != nil { return 0, err } } if value, ok := lookup("REPORT_LIMIT"); ok { n, err := strconv.Atoi(value) if err != nil { return 0, errors.New("invalid REPORT_LIMIT") } c.Limit = n } f := flag.NewFlagSet("report", flag.ContinueOnError) f.SetOutput(io.Discard) f.IntVar(&c.Limit, "limit", c.Limit, "maximum rows") if err := f.Parse(args); err != nil { return 0, err } if f.NArg() != 0 || c.Limit < 1 || c.Limit > 100 { return 0, errors.New("limit must be 1..100 with no operands") } return c.Limit, nil}func absent(string) (string, bool) { return "", false }func main() { lookup := func(string) (string, bool) { return "20", true } n, err := config([]byte(`{"limit":15}`), lookup, []string{"-limit=30"}) fmt.Println(n, err == nil)}IntVar starts with the merged value as the flag default. Explicit flags override it even when equal to the original default. Pass os.LookupEnv and bounded file bytes in a real CLI. Malformed provided layers fail immediately; final range checks run after merging.
Expected output:
30 trueMissing versus empty values
package main
import ( "encoding/json" "errors" "flag" "fmt" "io" "strconv")
func config(file []byte, lookup func(string) (string, bool), args []string) (int, error) { c := struct { Limit int `json:"limit"` }{10} if len(file) > 0 { if err := json.Unmarshal(file, &c); err != nil { return 0, err } } if value, ok := lookup("REPORT_LIMIT"); ok { n, err := strconv.Atoi(value) if err != nil { return 0, errors.New("invalid REPORT_LIMIT") } c.Limit = n } f := flag.NewFlagSet("report", flag.ContinueOnError) f.SetOutput(io.Discard) f.IntVar(&c.Limit, "limit", c.Limit, "maximum rows") if err := f.Parse(args); err != nil { return 0, err } if f.NArg() != 0 || c.Limit < 1 || c.Limit > 100 { return 0, errors.New("limit must be 1..100 with no operands") } return c.Limit, nil}func absent(string) (string, bool) { return "", false }func main() { n, err := config([]byte(`{"limit":15}`), absent, nil) fmt.Println(n, err == nil) _, err = config(nil, func(string) (string, bool) { return "", true }, nil) fmt.Println(err != nil)}LookupEnv distinguishes absent from present-empty. Unmarshal here tolerates unknown fields and treats JSON null for an int as no change. Strict formats must explicitly reject unwanted keys and nulls. Never print secrets in configuration diagnostics or pass them in command arguments.
Expected output:
15 truetrueTry it locally
With file limit 15 and absent environment, set -limit=10. Then test -limit=101.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
CLI 05: Load configuration and validate inputs
Check the lesson objective before moving on.
Which valid layer wins in this contract?
Why use LookupEnv?