viperconfig

package module
v1.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 14, 2026 License: MIT Imports: 6 Imported by: 0

README

go-viper-config

Generic, tag-based configuration loading and validation system built on Viper.

Features

One-line API: MustLoad(&Config{})
100% Generic: Works with any struct
Auto Validation: Tag-based validation
YAML + ENV: Automatic priority (ENV > YAML)
CSV Support: Lists from environment variables
Variable Expansion: ${VAR} support

Installation

go get github.com/senseizero/go-viper-config

Quick Start

package main

import "github.com/senseizero/go-viper-config/viperconfig"

type Config struct {
    Port    int      `mapstructure:"port" default:"8080"`
    Database DBConfig `mapstructure:"database"`
}

type DBConfig struct {
    Host string   `mapstructure:"host"`
    URLs []string `mapstructure:"urls"`
}

func main() {
    // One line loads everything!
    cfg := viperconfig.MustLoad(&Config{})
    
    // Use your config
    println(cfg.Port)
}

Supported Tags

  • mapstructure:"key" - Config key name
  • optional:"true" - Field is optional
  • default:"value" - Default value
  • validate:"positive,url" - Validation rules

Environment Variables

Priority: ENV > YAML

export APP_DATABASE_HOST="prod-db.example.com"
export APP_DATABASE_URLS="db1:5432,db2:5432,db3:5432"  # CSV support

Options

cfg := viperconfig.MustLoad(&Config{},
    viperconfig.WithEnvPrefix("MYAPP"),
    viperconfig.WithConfigName("myconfig"),
    viperconfig.WithConfigPaths("./config", "/etc/app"),
)

gRPC client fallback

The grpcclients subpackage dials a list of gRPC URLs in order and returns the first connection whose grpc_health_v1 Check succeeds. Paired with the CSV-to-slice env handling for *urls keys, this makes ephemeral PR environments trivially fall back to develop when a service isn't deployed in the PR stack:

export APP_SUKAUTO_URLS="pr-123-sukauto:9000,develop-sukauto:9000"
import (
    "github.com/senseizero/go-viper-config/grpcclients"
    "google.golang.org/grpc"
    "google.golang.org/grpc/credentials/insecure"
)

type Config struct {
    Sukauto struct {
        URLs []string `mapstructure:"urls"`
    } `mapstructure:"sukauto"`
}

cfg := viperconfig.MustLoad(&Config{})

conn, err := grpcclients.DialWithFallback(ctx, cfg.Sukauto.URLs,
    grpcclients.WithServiceName("sukauto"),
    grpcclients.WithDialOptions(grpc.WithTransportCredentials(insecure.NewCredentials())),
)
if err != nil { /* handle */ }
defer conn.Close()

sukauto := proto.NewSukautoClient(conn)

Options: WithDialOptions, WithHealthTimeout (default 5s), WithServiceName, WithLogger (*slog.Logger, defaults to slog.Default()). No async mode — if you want non-blocking startup, run DialWithFallback in a goroutine.

License

MIT

Documentation

Overview

Package viperconfig provides a generic, tag-based configuration loading and validation system built on top of Viper. It supports loading from YAML files and environment variables with automatic validation using struct tags.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Load

func Load[T any](cfg *T, opts ...Option) (*T, error)

Load loads and validates configuration from YAML file and environment variables Returns the populated config struct or an error

Example:

cfg, err := viperconfig.Load(&MyConfig{},/

viperconfig.WithEnvPrefix("MYAPP"),
viperconfig.WithConfigName("myconfig"),

)

func MustLoad

func MustLoad[T any](cfg *T, opts ...Option) *T

MustLoad loads and validates configuration, panics on error This is the simplest API - one line to load everything

Example:

cfg := viperconfig.MustLoad(&MyConfig{})/MyConfig{})

Types

type LoadOptions

type LoadOptions struct {
	// contains filtered or unexported fields
}

LoadOptions configures how configuration is loaded

type Option

type Option func(*LoadOptions)

Option is a functional option for configuring LoadOptions

func WithConfigName

func WithConfigName(name string) Option

WithConfigName sets the config file name without extension (default: "config")

func WithConfigPaths

func WithConfigPaths(paths ...string) Option

WithConfigPaths sets the paths to search for config file Replaces default paths entirely

func WithConfigType

func WithConfigType(configType string) Option

WithConfigType sets the config file type (default: "yaml") Supported: yaml, json, toml, etc.

func WithEnvPrefix

func WithEnvPrefix(prefix string) Option

WithEnvPrefix sets the environment variable prefix (default: "APP") Environment variables will be UPPERCASE(prefix)_KEY_NAME

type Validator

type Validator struct {
	// contains filtered or unexported fields
}

Validator provides configuration validation functionality

func NewValidator

func NewValidator(v *viper.Viper) *Validator

NewValidator creates a new Validator instance

func (*Validator) LoadAndValidate

func (val *Validator) LoadAndValidate(cfg interface{}) error

LoadAndValidate loads configuration from Viper into the provided struct and validates it The struct must have mapstructure tags for Viper unmarshaling

Supported tags:

  • mapstructure:"key_name" - maps to configuration key
  • optional:"true" - field can be empty (not required)
  • default:"value" - default value if not set
  • validate:"rule1,rule2" - validation rules (nonempty, positive, url, hostname)

By default, all fields are required unless marked optional or have a default value.

Directories

Path Synopsis
Package grpcclients provides a gRPC dial helper that tries a list of URLs in order and returns a connection to the first one whose grpc_health_v1 Check succeeds.
Package grpcclients provides a gRPC dial helper that tries a list of URLs in order and returns a connection to the first one whose grpc_health_v1 Check succeeds.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL