config

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Aug 6, 2020 License: Apache-2.0 Imports: 4 Imported by: 0

README

config

CircleCI Go Report Card codecov

Documentation

Overview

Package config read configuration from environment variables, optionally from YAML file.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Load

func Load(v interface{}, opts ...Option) error

Load v with data from environment variables or YAML file (if defined).

Example
package main

import (
	"fmt"
	"os"

	"github.com/pk60/config"
)

func main() {
	_ = os.Setenv("KEY_2", "from env")
	defer os.Unsetenv("KEY_2")

	type conf struct {
		Val  string
		Key1 string
		Key2 string `env:"KEY_2"`
		Key3 string `envDefault:"default value"`
	}

	c := &conf{
		Val: "value",
	}

	_ = config.Load(c, config.WithFilename("./testdata/valid.yml"))
	fmt.Printf("%#v", c)
}
Output:

&config_test.conf{Val:"value from yaml", Key1:"yaml value 1", Key2:"from env", Key3:"default value"}
Example (ParseEnvError)
package main

import (
	"fmt"
	"os"

	"github.com/pk60/config"
)

func main() {
	_ = os.Setenv("INVALID_DATA", "{1+2+3}")
	defer os.Unsetenv("INVALID_DATA")

	type conf struct {
		InvalidData *[]string `env:"INVALID_DATA"`
	}

	c := &conf{}

	err := config.Load(c)
	fmt.Printf("%v", err)
}
Output:

failed to parse environment variables: env: no parser found for field "InvalidData" of type "*[]string"
Example (ParseYAMLError)
package main

import (
	"fmt"

	"github.com/pk60/config"
)

func main() {
	type conf struct{}
	c := &conf{}

	err := config.Load(c, config.WithFilename("./testdata/invalid.yml"))
	fmt.Print(err.Error())
}
Output:

failed to unmarshal YAML file: ./testdata/invalid.yml: yaml: line 2: mapping values are not allowed in this context
Example (ReadYAMLError)
package main

import (
	"fmt"

	"github.com/pk60/config"
)

func main() {
	type conf struct{}
	c := &conf{}

	err := config.Load(c, config.WithFilename("./non_existing_config.yml"))
	fmt.Print(err.Error())
}
Output:

failed to read YAML file: open ./non_existing_config.yml: no such file or directory

Types

type Option

type Option func(*option)

func WithFilename

func WithFilename(filename string) Option

Jump to

Keyboard shortcuts

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