Go Academy · Lesson

Environment Variables

Override config from env.

Lesson 2 of 413 steps

Environment Variables is a free Go Academy lesson on CoddyKit. This is lesson 2 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, and your progress syncs across the web and the CoddyKit app. The Go Academy course includes 4 lessons in total.

Why Environment Variables

The Twelve-Factor App methodology recommends storing config in the environment. Env vars let the same binary behave differently across dev, staging, and production without editing files.

Viper can layer env vars on top of file config.

Precedence Order

Viper resolves a key by checking sources in priority order (highest first):

  • Explicit Set calls
  • Flags
  • Environment variables
  • Config file
  • Defaults

So an env var overrides the file but loses to an explicit Set.

Turning On Env Support

viper.AutomaticEnv() tells Viper to check environment variables for any key you request. After this, viper.GetString("port") will look at the PORT env var.

viper.AutomaticEnv()
port := viper.GetString("port")

Adding a Prefix

To avoid clashing with unrelated env vars, set a prefix:

  • viper.SetEnvPrefix("myapp")
  • Now key port maps to env var MYAPP_PORT

Viper uppercases the key and prepends the prefix with an underscore.

viper.SetEnvPrefix("myapp")
viper.AutomaticEnv()
fmt.Println(viper.GetString("port")) // reads MYAPP_PORT

Handling Nested Keys

Env vars cannot contain dots. Use a key replacer to map dotted keys to underscores, so server.port becomes SERVER_PORT.

replacer := strings.NewReplacer(".", "_")
viper.SetEnvKeyReplacer(replacer)
viper.AutomaticEnv()
// server.port -> SERVER_PORT

Binding a Single Variable

Instead of automatic mode, you can bind one key explicitly with viper.BindEnv. This is useful when the env var name does not follow your prefix convention.

viper.BindEnv("id", "ACCOUNT_ID")
fmt.Println(viper.GetString("id"))

The Standard Library os Package

Under the hood this reads from the process environment, exposed by the standard library via os.Getenv and os.LookupEnv.

  • os.Getenv returns an empty string if unset
  • os.LookupEnv returns a second bool telling you if it was present
val, ok := os.LookupEnv("PORT")
if !ok {
    val = "8080" // default
}

Setting Env Vars in Go

You can set env vars programmatically for tests or defaults with os.Setenv. This is exactly what we use to demonstrate the override behavior next.

os.Setenv("MYAPP_PORT", "9090")

Empty vs Unset

Beware: an env var set to an empty string is still present. os.LookupEnv returns ("", true). If you only use os.Getenv you cannot tell empty from unset, which matters for boolean-like flags.

os.Setenv("FEATURE", "")
v, ok := os.LookupEnv("FEATURE")
fmt.Println(v == "", ok) // true true

Putting It Together (Concept)

A typical startup flow: read the file for defaults, then call AutomaticEnv so deployment env vars win. Ops can change MYAPP_PORT without touching the YAML.

viper.SetConfigName("config")
viper.ReadInConfig()
viper.SetEnvPrefix("myapp")
viper.AutomaticEnv()
fmt.Println(viper.GetInt("port"))

Runnable: Env Override Demo

This standard-library program mimics Viper precedence: a file default, overridden by the environment.

package main

import (
    "fmt"
    "os"
)

func get(key, fileDefault string) string {
    if v, ok := os.LookupEnv(key); ok {
        return v
    }
    return fileDefault
}

func main() {
    os.Setenv("PORT", "9090")
    fmt.Println("port:", get("PORT", "8080"))
    fmt.Println("host:", get("HOST", "localhost"))
}

Quick Check

Test your understanding of env var configuration.

Recap

You learned to override config from the environment:

  • Env vars sit high in Viper precedence, above the file
  • AutomaticEnv + SetEnvPrefix map keys to PREFIX_KEY
  • Use SetEnvKeyReplacer for nested dotted keys
  • The standard library backs this with os.Getenv / os.LookupEnv
Free to start

Learn Go with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

Is the “Environment Variables” lesson free?

Yes — any 3 lessons of the Go Academy learning path, including “Environment Variables”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Go Academy course includes 4 lessons in total.

What will I learn in “Environment Variables”?

Override config from env. You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 4.

How long does the “Environment Variables” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Reading Config Files
  2. Environment Variables
  3. Defaults and Watching
  4. Binding to Structs
← Back to Go Academy