0Pricing
Go Academy · Lesson

Defaults and Watching

Set defaults and hot reload.

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

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

Frequently asked questions

Is the “Defaults and Watching” lesson free?

Yes — the full text of “Defaults and Watching” 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 “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; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

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