viperenv

package module
v2.1.0 Latest Latest
Warning

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

Go to latest
Published: Jan 12, 2024 License: MIT Imports: 4 Imported by: 0

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.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Bind

func Bind(outPtr interface{}, v *viper.Viper, options BindOptions) error

Bind binds the env vars to the config.

Parameters:

  • outPtr: The pointer to the config struct.
  • v: The viper instance.
  • options: The options.

Types

type BindOptions

type BindOptions struct {
	AutoEnv        bool              // Whether to call viper.AutomaticEnv() or not.
	EnvPrefix      string            // The env prefix; calls viper.SetEnvPrefix() if not empty.
	AllowEmptyEnv  bool              // Whether to call viper.AllowEmptyEnv() or not.
	EnvKeyReplacer *strings.Replacer // The env key replacer; calls viper.SetEnvKeyReplacer() if not nil.
}

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

Jump to

Keyboard shortcuts

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