Categorygithub.com/bartventer/viperenv/v2
modulepackage
2.1.0
Repository: https://github.com/bartventer/viperenv.git
Documentation: pkg.go.dev

# README

viperenv

Go Reference Go Report Card Coverage Status Build License

viperenv is a Go package that provides a simple way to bind environment variables to a struct using Viper. It allows you to define a struct with tags that specify the environment variable names. You can then use the viperenv.Bind() function to bind the environment variables to the struct. The upside of this is that you don't have to manually set each environment variable with viper.BindEnv(), you can just bind them all at once.

Installation

To install viperenv, use go get:

go get github.com/bartventer/viperenv/v2

Usage

package main

import (
    "fmt"
    "log"

    "github.com/spf13/viper"
    "github.com/bartventer/viperenv/v2"
)

type Config struct {
    Host string `env:"HOST,default=localhost" mapstructure:"host"`
    Port int    `env:"PORT" mapstructure:"port"`
}

func main() {
    // Set environment variables
    os.Setenv("PORT", "8080")

    // Set up viper
    v := viper.New()
    var config Config
    # ... set up viper, and read config file, etc.
    err := viperenv.Bind(&config, v, viperenv.BindOptions{
        AutoEnv: true,
    })
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(config.Host) // "localhost"
    fmt.Println(config.Port) // "8080"
}

License

This project is licensed under the MIT License. See the LICENSE file for details.

# Functions

Bind binds the env vars to the config.

# Structs

BindOptions represents various options for binding env vars to the config.