Skip to content

Go Viper Env

DodaTech 1 min read

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

Viper environment binding -- Bind Viper config keys to environment variables for twelve-factor app configuration.

The Problem

Viper does not read OS environment variables automatically. Call AutomaticEnv() or BindEnv to map env vars to config keys.

Wrong

viper.SetConfigName("config")
viper.ReadInConfig()
host := viper.GetString("DATABASE_HOST") // Empty!

Output:

// No env vars bound. Returns empty.
viper.AutomaticEnv()
viper.SetEnvPrefix("APP")
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
// DATABASE_HOST env var maps to config key database.host
host := viper.GetString("database.host")

Output:

// DATABASE_HOST=localhost -> database.host = "localhost"

Prevention

  • Use AutomaticEnv() to bind all env vars
  • Use SetEnvPrefix("APP") to prefix: APP_DATABASE_HOST
  • Use SetEnvKeyReplacer to map dots to underscores
  • Env overrides config file values
  • Use BindEnv for specific key binding

Common Mistakes with viper env

  1. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  2. Non-exhaustive pattern matches that compile with warnings then crash at runtime
  3. Misunderstanding that String is [Char] with poor performance for large text operations

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

**What is the environment variable priority?**

Explicit BindEnv > AutomaticEnv > config file > defaults.

How to bind a specific key?

viper.BindEnv("database.host", "DB_HOST").

Does env binding support slices?

Yes. Use comma-separated values or viper's decoder.


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