config

package
v0.0.0-...-edcedff Latest Latest
Warning

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

Go to latest
Published: Jul 24, 2020 License: Apache-2.0 Imports: 5 Imported by: 0

Documentation

Overview

Package config is a https://github.com/spf13/viper wrapper with some convention.

Example
package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"

	"github.com/foodarchive/truffls/pkg/config"
	"github.com/pkg/errors"
	"github.com/spf13/pflag"
)

type (
	ServerConfig struct {
		Addr string
		Port uint
	}

	Config struct {
		AppName string `config:"app_name"`
		Env     string
		Debug   bool
		Server  ServerConfig `config:"http_server"`
	}
)

var (
	configBytes = []byte(`
app_name: foo
debug: true
http_server:
  addr: localhost
  port: 3000`)
)

func main() {
	configPath := fmt.Sprintf("%s/config_sample.yml", filepath.Dir("."))
	if err := ioutil.WriteFile(configPath, configBytes, 0644); err != nil {
		log.Fatal(errors.Wrap(err, "fail to write config file"))
	}

	defer func() {
		_ = os.Remove(configPath)
	}()

	_ = pflag.String("env", "development", "setup app env")
	pflag.Parse()

	_ = os.Setenv("SIMPLE_APP_NAME", "simple")
	defer func() {
		_ = os.Unsetenv("SIMPLE_APP_NAME")
	}()

	_ = config.Load("simple", configPath)
	_ = config.BindFlags(pflag.Lookup("env"))

	var c Config
	if err := config.Unmarshal(&c); err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%+v\n", c)
}
Output:

{AppName:simple Env:development Debug:true Server:{Addr:localhost Port:3000}}

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrEmptyNamespace thrown when namespace is not provided.
	ErrEmptyNamespace = errors.New("config namespace must be provided")
)

Functions

func BindFlags

func BindFlags(flags ...*Flag) error

BindFlags binds multiple keys to pflag.Flag.

func Load

func Load(namespace, cfgFile string) error

Load loading configuration from yaml file with namespace.

func Unmarshal

func Unmarshal(v interface{}) error

Unmarshal unmarshals the config into a Struct.

Types

type Flag

type Flag = pflag.Flag

Flag is pflag.Flag alias.

Jump to

Keyboard shortcuts

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