config

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 21, 2021 License: MIT Imports: 11 Imported by: 1

README

Build Status Go Report Card

go-config

Offers a rich configuration file handler.

  • Read configuration files with ease
  • Bind CLI flags
  • Bind environment variables
  • Watch file (or files) and get notified if they change

Uses the following precedence order:

  • flag
  • env
  • toml
flag env toml result
flag
flag
flag
env
flag
env
toml

If flag is set and not given, it will parse env or toml according to their precedence order (otherwise flag default).

Basic Example

Call the Load() method to load a config.

    type MyConfig struct {
        Key1    string   `toml:"key1"`
        Key2    string   `toml:"key2"`
        Port    int      `toml:"-" flag:"port"`
        Secret  string   `toml:"-" flag:"-" env:"secret"`
    }

    _ = flag.Int("port", 8080, "Port to listen on") // <- notice no variable
    flag.Parse()

    var cfg MyConfig
    err := config.Load("./config.toml", &cfg)

    fmt.Printf("Loaded config: %#v\n", cfg)
    // Port info is in cfg.Port, parsed from `-port` param
    // Secret info is in cfg.Secret, parsed from `secret` environment variable

File Watching

Call Watch() method, get a notification channel and listen...

    ch, err := config.Watch(context.Background(), "config.toml")

    for {
        select {
        case e := <-ch:
        	if e != nil {
        		fmt.Printf("Error occured watching file: %v", e)
        		continue
        	}

            fmt.Println("Changed, reloading...")
            var cfg MyConfig
            err := config.Load("config.toml", &cfg)
            fmt.Printf("Loaded: %v %#v\n", err, cfg)
            // Handle cfg...
        }
    }

Documentation

Overview

Package config offers a rich configuration file handler.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Load

func Load(filepath string, dst interface{}) error

Load loads filepath into dst. It also handles "flag" binding.

func Watch

func Watch(ctx context.Context, pathtofile string) (<-chan error, error)

Watch starts watching the given file for changes, and returns a channel to get notified on. Errors are also passed through this channel: Receiving a nil from the channel indicates the file is updated.

Types

This section is empty.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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