Go Viper Defaults
In this tutorial, you'll learn about Viper: Missing Defaults. We cover key concepts, practical examples, and best practices.
Default configuration -- Use viper.SetDefault to provide fallback values for missing configuration keys.
The Problem
viper.GetString on a missing key returns "". Use SetDefault to provide sensible defaults that are overridden by config file or env vars.
Wrong
port := viper.GetInt("server.port")
// port is 0 if not configured. Server fails to start.
Output:
// Zero value. No indication of using default.
Right
viper.SetDefault("server.port", 8080)
viper.SetDefault("server.host", "0.0.0.0")
viper.SetDefault("log.level", "info")
port := viper.GetInt("server.port") // 8080 if not set
Output:
// Defaults used. Config file or env can override.
Prevention
- Set sensible defaults before reading config files
- Defaults have lowest priority (overridden by file, env, flags)
- Use SetDefault for every configuration key
- Document defaults in code for self-documenting configuration
- Defaults can be complex types (maps, slices)
Common Mistakes with viper defaults
- Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro