Skip to content

Go Viper Load

DodaTech 1 min read

In this tutorial, you'll learn about Viper: Config Not Loading. We cover key concepts, practical examples, and best practices.

Viper configuration -- Load application configuration correctly by setting config name, path, and type before calling ReadInConfig.

The Problem

Viper requires config name, type, and at least one path. Calling viper.GetString before configuration is read returns empty strings.

Wrong

viper.GetString("database.host") // Empty! Config not loaded.

Output:

// Returns empty string. No error indication.
viper.SetConfigName("config")
viper.SetConfigType("yaml")
viper.AddConfigPath(".")
viper.AddConfigPath("/etc/app/")
if err := viper.ReadInConfig(); err != nil {
    log.Fatal("Failed to read config:", err)
}
host := viper.GetString("database.host")

Output:

// Config loaded. GetString returns actual value.

Prevention

  • Always call ReadInConfig before accessing values
  • SetConfigName (without extension), SetConfigType, AddConfigPath
  • Add multiple config paths for fallback
  • Use viper.WatchConfig() for hot reload
  • Check for errors from ReadInConfig

Common Mistakes with viper load

  1. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
  2. Using return to exit a function early instead of wrapping a pure value in the monad
  3. 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

**Does Viper support defaults?**

Yes. viper.SetDefault("key", "value") before ReadInConfig.

Can Viper read from remote sources?

Yes. etcd, Consul, Firestore via remote providers.

What formats does Viper support?

JSON, YAML, TOML, HCL, INI, envfile, Java properties.


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