0Pricing
Go Academy · Lesson

Environment Variables

Override config from env.

Environment Variables is a free Go Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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

Frequently asked questions

Is the “Environment Variables” lesson free?

Yes — the full text of “Environment Variables” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.

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; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

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