Viper Environment Configuration Layering

Layer application config with Viper across files, environment variables with key replacer, and overrides bound to flags.

GoConfig Management

Code

gosnippet
72 lines
package main

import (
	"fmt"
	"strings"
	"time"

	"github.com/spf13/viper"
)

type ServerConfig struct {
	Host         string
	Port         int
	Timeout      time.Duration
	DatabaseURL  string
	ReplicaHosts []string
}

// precedence: flags > env > config file > defaults
func loadConfig(path string) (*ServerConfig, error) {
	v := viper.New()

	v.SetConfigName("config")
	v.SetConfigType("yaml")
	v.SetConfigFile(path)

	v.SetEnvPrefix("SRV")
	v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
	v.AutomaticEnv()

	v.SetDefault("host", "0.0.0.0")
	v.SetDefault("port", 8080)
	v.SetDefault("timeout", "5s")
	v.SetDefault("replicaHosts", []string{})

	if err := v.ReadInConfig(); err != nil {
		if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
			return nil, fmt.Errorf("read config: %w", err)
		}
		// 配置文件缺失不算错:全部回退到环境变量与默认值
	}

	if err := v.Validate(); err != nil {
		return nil, fmt.Errorf("validate: %w", err)
	}

	cfg := &ServerConfig{
		Host:        v.GetString("host"),
		Port:        v.GetInt("port"),
		DatabaseURL: v.GetString("database.url"),
	}
	if raw := v.GetString("timeout"); raw != "" {
		d, err := time.ParseDuration(raw)
		if err != nil {
			return nil, fmt.Errorf("invalid timeout %q: %w", raw, err)
		}
		cfg.Timeout = d
	}
	if replicas := v.GetStringSlice("replicaHosts"); len(replicas) > 0 {
		cfg.ReplicaHosts = replicas
	}

	if cfg.Port < 1 || cfg.Port > 65535 {
		return nil, fmt.Errorf("port %d out of range", cfg.Port)
	}
	return cfg, nil
}

func main() {
	cfg, err := loadConfig("configs/config.yaml")
	fmt.Println(cfg, err)
}

Inside the snippet

The working surface is the functions loadConfig and main — everything else is wiring.

Failures are values here: 3 sites check err and decide instead of letting one propagate.

What to watch for

  • Dependency check: github.com/spf13/viper — not built-in, must be present in the project.
  • Errors are ordinary return values; skipping the err check means using a zero value silently.

Putting it to use

The primary signature is func loadConfig(path string) (*ServerConfig, error)

The entry point wires loadConfig together — run it once and the whole demo flows.

Core lines

return nil, fmt.Errorf("invalid timeout %q: %w", raw, err)
return nil, fmt.Errorf("read config: %w", err)
return nil, fmt.Errorf("validate: %w", err)

Interactive Tools for This Topic

FAQ

What happens when a call fails?
As returned `error` values, checked at 3 sites — callers must branch on `err` before using the other return values. No panics or exceptions in the snippet.
What does this need from the package registry?
These are real dependencies: `github.com/spf13/viper`. Without it the snippet will not load.