ko

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 2, 2022 License: MIT Imports: 9 Imported by: 0

README

ko GoDoc Go Report Card Build Status

ko is a package for golang that allows to use configuration files with any format that can be unmarshalled to Go struct like TOML/YAML/JSON.

Supported tags

ko is controlled by Go struct tags, following tags are supported:

  • required - if specified as true, will trigger an error if no value specified for field.
  • env - read value from specified environment variable if no value specified in config file.
  • default - specifies default value for field, specified value will be unmarshalled using yaml.Unmarshal.

Usage

type Config struct {
    Hostname string `default:"localhost"`
    Username string `required:"true"`
    Port     int    `env:"PORT" default:"8086"`
    Password string
}

var config Config
err := ko.Load("app.conf", &config)
if err != nil  {
    panic(err)
}

Will return error if no value for Username field specified, Hostname will be localhost if no value specified in config file, Password will be empty if no value specified, no error will be returned for this field. If PORT environment variable is specified, Port field will contain its value, if given environment variable doesn't exist, default value 8086 will be used.

Also, you can pass custom unmarshaller if you use custom format.

type Config struct {
    Hostname string `default:"localhost"`
    Username string `required:"true"`
    Password string
}

var config Config
err := ko.Load("app.json", &config, json.Unmarshal)
if err != nil {
    panic(err)
}

The package doesn't support maps.

License

MIT.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Load

func Load(
	path string,
	resource interface{},
	opts ...interface{},
) error

Load resource data from specified file. unmarshaller variable can be passed if you want to use custom unmarshaller, by default will be used DefaultUnmarshaller (toml.Unmarshal)

Types

type RequireFile

type RequireFile bool

RequireFile is an option for Load method which can be used to skip non-existing file and load all default values for the config fields.

type Unmarshaller

type Unmarshaller func([]byte, interface{}) error

Unmarshaller represents signature of function that will be used for unmarshalling raw file data to structured data. See:

json.Unmarshal
toml.Unmarshal
var DefaultUnmarshaller Unmarshaller = toml.Unmarshal

DefaultUnmarshaller will be used for unmarshalling if no unmarshaller specified.

Jump to

Keyboard shortcuts

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