ProgramGuru

Environment Variables

Start with Environment Variables

Environment variables supply configuration to a running process without hard-coding a value in the source file.

What you’ll learn

  • Explain the main purpose of environment variables.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

os.Getenv returns the variable’s value or an empty string if absent, while os.LookupEnv returns the value and a boolean indicating presence. os.Setenv changes the current process’s environment, which can be useful for controlled tests.

Use environment variables for configuration such as a port or application mode, but treat secret values carefully: prevent accidental printing and avoid committing .env files containing credentials.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for envA condition branches into true or false paths before continuing.APP_PORT exists?TRUEFALSEUse configured portUse default portStart application
Trace control flow in the order shown, then compare it with the program.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import (
	"fmt"
	"os"
)

func main() {
	const key = "GO_COURSE_MODE_DEMO"
	if err := os.Setenv(key, "development"); err != nil {
		panic(err)
	}
	mode, ok := os.LookupEnv(key)
	fmt.Println("Set:", ok)
	fmt.Println("Mode:", mode)
}

Output

Set: true
Mode: development

Trace what the program does

The example sets a known process variable to development, then LookupEnv retrieves it. This ensures deterministic output regardless of the parent shell configuration.

Avoid common mistakes

  • Environment variable names and case handling can vary between systems.
  • Avoid printing secrets or assuming environment variables are a secure encrypted vault.

Try it yourself

Read an optional APP_PORT environment variable and default to 8080 when it is unset.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

Which function distinguishes unset from set-but-empty?
Choose one answer. You can try again.

Answer and explanation

os.LookupEnv

Correct. The example sets a known process variable to development, then LookupEnv retrieves it.

What you should remember

You have practiced Environment Variables in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: JSON Encoding and Decoding →