Lesson 33 of 60 · Go
Working with Environment Variables
Duration: 10 minutes
Configuration via Env
This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.
Use os.Getenv and os.LookupEnv.
port := os.Getenv("PORT")
if port == "" { port = "8080" }
Parsing numbers safely
if pStr, ok := os.LookupEnv("MAX_CONN"); ok {
if p, err := strconv.Atoi(pStr); err == nil {
maxConn = p
}
}
Loading .env files (third‑party)
$ go get github.com/joho/godotenv
import "github.com/joho/godotenv"
godotenv.Load() // loads .env into process env