Understand the contract
Environment variables supply strings to a process. os.LookupEnv distinguishes an unset variable from a variable explicitly set to an empty string. Read configuration at startup, parse it into typed values and reject invalid settings before starting background work or serving requests.
The example chooses a default only when APP_WORKERS is absent. If it is present, Atoi must succeed and the value must stay within a defined range. Bounding the worker count prevents an accidental configuration value from creating an unreasonable number of goroutines later.
Work through the example
With no variable set, the output is two. Setting APP_WORKERS to four prints four; an empty string or zero is rejected. The upper bound of sixteen is an educational policy for this example, not a universal recommendation for Go services or a performance measurement.
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
workers := 2
if raw, set := os.LookupEnv("APP_WORKERS"); set {
n, err := strconv.Atoi(raw)
if err != nil || n < 1 || n > 16 {
fmt.Println("APP_WORKERS must be an integer from 1 to 16"); return
}
workers = n
}
fmt.Println(workers)
}Watch this boundary
Do not print the full environment to troubleshoot one setting, because it can contain secrets. Report the setting name and validation problem instead. Read and validate once where practical, then pass a configuration value into the code that uses it rather than scattering environment reads across business logic.
Practice with a changed input
Try unset, empty, negative, nonnumeric and out-of-range inputs. Extract parsing into a function so the validation rules can be tested without modifying the process environment.
Lesson 37 of 50
View the full Go basics seriesReferences & further reading
Need help with your Go backend?
I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.
Explore Go consulting services