Go Academy · Lesson

Defaults and Watching

Set defaults and hot reload.

Lesson 3 of 413 steps

Defaults and Watching is a free Go Academy lesson on CoddyKit. This is lesson 3 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.

Sensible Defaults

Good config systems work even when nothing is set. Defaults give every key a fallback so your program never crashes on a missing value.

Viper provides SetDefault for this, and it sits at the bottom of the precedence chain.

Setting Defaults

Register defaults before reading the file. Any source (file, env, flag) overrides these.

viper.SetDefault("port", 8080)
viper.SetDefault("logLevel", "info")
fmt.Println(viper.GetInt("port"))

Why Defaults Help

Defaults shrink your config files: ops only override what differs from the norm. They also document the expected shape of configuration directly in code.

Hot Reloading With WatchConfig

Sometimes you want config changes to take effect without restarting. viper.WatchConfig() watches the file for changes using fsnotify.

viper.WatchConfig()

Reacting to Changes

Register a callback to run when the file changes:

viper.OnConfigChange(func(e fsnotify.Event) {
    fmt.Println("config changed:", e.Name)
})
viper.WatchConfig()

What Hot Reload Is Good For

Hot reload shines for values that are safe to change live:

  • Log verbosity
  • Feature flags
  • Rate limits

Avoid hot-reloading things like the listen port or database DSN, which usually require a restart.

Thread Safety Concern

When config can change at runtime, multiple goroutines may read it. Viper getters are safe to call concurrently, but if you cache values into your own variables, protect them with a mutex or atomic value.

var cfg atomic.Value // stores a Config struct
cfg.Store(loadConfig())

Modeling Defaults Without Viper

You can express the same defaulting idea in plain Go: a function that returns the value if present, else a fallback.

func intOr(m map[string]int, key string, def int) int {
    if v, ok := m[key]; ok {
        return v
    }
    return def
}

Validation After Reload

Always validate after a reload before applying. A typo in the file should keep the old good config, not crash the running service. Log the error and keep serving.

newCfg, err := load()
if err != nil {
    log.Println("bad config, keeping current:", err)
    return
}
current.Store(newCfg)

Simulating a Reload

Conceptually, a reload re-reads the source and swaps the active config. The watcher just triggers that swap when the file mtime changes. The next runnable demo shows the value changing.

Runnable: Defaults and Reload

This self-contained program shows defaulting logic, then a simulated reload changing a value.

package main

import "fmt"

func get(m map[string]int, k string, def int) int {
    if v, ok := m[k]; ok {
        return v
    }
    return def
}

func main() {
    cfg := map[string]int{}
    fmt.Println("port (default):", get(cfg, "port", 8080))
    cfg["port"] = 9090 // simulated reload
    fmt.Println("port (reloaded):", get(cfg, "port", 8080))
}

Quick Check

Test your understanding of defaults and watching.

Recap

You learned defaults and hot reloading:

  • SetDefault provides fallbacks at the lowest precedence
  • WatchConfig + OnConfigChange enable live reloads
  • Only hot-reload values that are safe to change at runtime
  • Protect cached config with atomics/mutexes and validate before applying
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 “Defaults and Watching” lesson free?

Yes — any 3 lessons of the Go Academy learning path, including “Defaults and Watching”, 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 “Defaults and Watching”?

Set defaults and hot reload. 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 3 of 4.

How long does the “Defaults and Watching” 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