config

package
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Mar 9, 2022 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package config provides an application configuration system.

Usage

First, config need to initialize at the beginning.
if err := config.Init(); err != nil {
  // Handle error.
}

Then to read config, just unmarshal it to a struct or map:

cfg := serverConfig
  Port: 8080,
  Name: "default",
}
if err := config.Unmarshal("server", &ac); err != nil {
  // handle error
}

Configuration Source

It loads configuration from the following sources. Each item takes precedence over the item below it:

  • command line flag if it's defined like below: flag.String("foo.bar", "default value", "config `bar`")
  • environment variables which matches the following format: prefix + "_" + the key name in ALL CAPS. For example, FOO_BAR is the name of environment variable to foo.bar.
  • config file specified by WithFile and WithFS.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Init added in v0.3.0

func Init(opts ...Option) error

Init initialize application configuration.

func Unmarshal

func Unmarshal(prefix string, target interface{}) error

Unmarshal unmarshalls the config with prefix into a (embedded) struct pointed to by target.

It also supports unmarshaling values which uses mapstructure tags by default. See https://github.com/mitchellh/mapstructure.

Example
package main

import (
	"fmt"
	"os"

	"github.com/ktong/nilgo/config"
)

func main() {
	_ = os.Setenv("SOURCE", "env")
	defer os.Clearenv()

	_ = config.Init()

	var c struct {
		Source string
	}

	_ = config.Unmarshal("", &c)
	fmt.Println(c.Source)

}
Output:

env

Types

type Option

type Option func(*options)

Option configures how it loads application configuration.

func WithFS

func WithFS(fs fs.FS) Option

WithFS specifies the fs.FS for config files.

The default is file system from OS.

func WithFile

func WithFile(path string) Option

WithFile explicitly defines the path, name of the config file.

Example
package main

import (
	"fmt"
	"testing/fstest"

	"github.com/ktong/nilgo/config"
)

func main() {
	mapFS := fstest.MapFS{
		"config.yaml": {
			Data: []byte("file:\n  source: embed"),
		},
	}

	_ = config.Init(
		config.WithFile("config.yaml"),
		config.WithFS(mapFS),
	)

	var source string
	_ = config.Unmarshal("file.source", &source)
	fmt.Println(source)

}
Output:

embed

Jump to

Keyboard shortcuts

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