config

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Dec 9, 2019 License: MIT Imports: 11 Imported by: 4

README

go-config Build Status

go-config allows to initialize configuration in flexible way using from default, file, environment variables value.

Initialization

Done in three steps:

  1. init with value from default tag
  2. merge with config file if filepath is provided
  3. override with environment variables which stored under envconfig tag
Supported file extensions
  • json
Supported types
  • Standard types: bool, float, int(uint), slice, string
  • time.Duration, time.Time: full support with aliases config.Duration, config.Time
  • Custom types, slice of custom types
Usage
Default value
type Server struct {
    Addr string `default:"localhost:8080"`
}
Environment value
type Server struct {
    Addr string `envconfig:"SERVER_ADDR"`
}
Combined default, json, env
type Server struct {
    Addr string `json:"addr" envconfig:"SERVER_ADDR" default:"localhost:8080"`
}
Slice

Default strings separator is comma.

REDIS_ADDR=127.0.0.1:6377,127.0.0.1:6378,127.0.0.1:6379
type Redis struct {
    Addrs []string `json:"addrs" envconfig:"REDIS_ADDR" default:"localhost:6378,localhost:6379"`
}

Slice of structs could be parsed from environment by defining envprefix.
Every ENV group override element stored at index of slice or append new one.
Sparse slices are not allowed.

var cfg struct {
...
Replicas []Postgres `json:"replicas" envprefix:"REPLICAS"`
...
}

Environment key should has next pattern:
${envprefix}_${index}_${envconfig} or ${envprefix}_${index}_${StructFieldName}

REPLICAS_0_POSTGRES_USER=replica REPLICAS_2_USER=replica
time.Duration, time.Time

In case using json file you have to use aliases config.Duration, config.Time, that properly unmarshal it self

type NATS struct {
    ...
    ReconnectInterval config.Duration `json:"reconnect_interval" envconfig:"NATS_RECONNECT_INTERVAL" default:"2s"`
}

Otherwise time.Duration, time.Time might be used directly:

var cfg struct {
    ReadTimeout  time.Duration `envconfig:"READ_TIMEOUT"  default:"1s"`
    WriteTimeout time.Duration `envconfig:"WRITE_TIMEOUT" default:"10s"`
}

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrNotSlice       = errors.New("should be a slice")
	ErrNotSettable    = errors.New("should be settable")
	ErrPrefixRequired = errors.New("prefix is required")
)
View Source
var (
	ErrNotPointer = errors.New("should be a pointer")
	ErrNotStruct  = errors.New("should be a structure")
)
View Source
var Setenv = os.Setenv
View Source
var Unsetenv = os.Unsetenv

Functions

func Init

func Init(config interface{}, filename string) error

Init reads and init configuration to `config` variable, which must be a reference of struct

Example
type Server struct {
	Addr string `json:"addr" envconfig:"SERVER_ADDR" default:"localhost:8080"`
}

type Postgres struct {
	Host     string `json:"host"     envconfig:"POSTGRES_HOST"     default:"localhost"`
	Port     string `json:"port"     envconfig:"POSTGRES_PORT"     default:"5432"`
	User     string `json:"user"     envconfig:"POSTGRES_USER"     default:"postgres"`
	Password string `json:"password" envconfig:"POSTGRES_PASSWORD" default:"12345"`
}

type Redis struct {
	Addrs []string `json:"addrs" envconfig:"REDIS_ADDR" default:"localhost:6379"`
}

type NATS struct {
	ServerURL               string          `json:"server_url"                envconfig:"NATS_SERVER_URL"             default:"nats://localhost:4222"`
	MaxReconnectionAttempts int             `json:"max_reconnection_attempts" envconfig:"NATS_MAX_RECONNECT_ATTEMPTS" default:"5"`
	ReconnectInterval       config.Duration `json:"reconnect_interval"        envconfig:"NATS_RECONNECT_INTERVAL"     default:"2s"`
}

type Websocket struct {
	Port string `json:"port" envconfig:"WEBSOCKET_PORT" default:"9876"`
}

var cfg struct {
	Version   string     `envconfig:"VERSION" default:"0"`
	Server    Server     `json:"server"`
	Postgres  Postgres   `json:"postgres"`
	Replicas  []Postgres `json:"replicas" envprefix:"REPLICAS"`
	Redis     Redis      `json:"redis"`
	NATS      NATS       `json:"nats"`
	Websocket Websocket  `json:"websocket"`
}

if err := config.Init(&cfg, "testdata/config.json"); err != nil {
	log.Fatalln(err)
}

fmt.Println(cfg)
Output:
{0.0.1 {localhost:8080} {localhost 5432 postgres 12345} [{localhost 5433 replica0 12345} {localhost 5433 replica1 12345}] {[127.0.0.1:6377 127.0.0.1:6378 127.0.0.1:6379]} {nats://localhost:4222 5 2000000000} {9876}}

func ToCamelCase

func ToCamelCase(str string) string

ToCamelCase converts string to camel case

Types

type Duration

type Duration time.Duration

Duration provides marshal/unmarshal of duration as a string

func (Duration) MarshalJSON

func (d Duration) MarshalJSON() ([]byte, error)

MarshalJSON Duration as a string

func (*Duration) UnmarshalJSON

func (d *Duration) UnmarshalJSON(b []byte) error

UnmarshalJSON Duration from float64/string

Jump to

Keyboard shortcuts

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