go-options: github.com/mreiferson/go-options Index | Examples | Files

package options

import "github.com/mreiferson/go-options"

options resolves configuration values set via command line flags, config files, and default struct values

Index

Examples

Package Files

options.go

func Resolve Uses

func Resolve(options interface{}, flagSet *flag.FlagSet, cfg map[string]interface{})

Resolve combines configuration values set via command line flags (FlagSet) or an externally parsed config file (map) onto an options struct.

The options struct supports struct tags "flag", "cfg", and "deprecated", ex:

type Options struct {
	MaxSize     int64         `flag:"max-size" cfg:"max_size"`
	Timeout     time.Duration `flag:"timeout" cfg:"timeout"`
	Description string        `flag:"description" cfg:"description"`
}

Values are resolved with the following priorities (highest to lowest):

1. Command line flag
2. Deprecated command line flag
3. Config file value
4. Get() value (if Getter)
5. Options struct default value

Code:

package main

import (
    "flag"
    "fmt"
    "time"

    "github.com/mreiferson/go-options"
)

type Options struct {
    MaxSize     int64         `flag:"max-size" cfg:"max_size"`
    Timeout     time.Duration `flag:"timeout" cfg:"timeout"`
    Description string        `flag:"description" cfg:"description"`
}

func main() {
    flagSet := flag.NewFlagSet("example", flag.ExitOnError)
    flagSet.Int64("max-size", 1024768, "maximum size")
    flagSet.Duration("timeout", 1*time.Hour, "timeout setting")
    flagSet.String("description", "", "description info")
    // parse command line arguments here
    // flagSet.Parse(os.Args[1:])
    flagSet.Parse([]string{"-timeout=5s"})

    opts := &Options{
        MaxSize: 1,
        Timeout: time.Second,
    }
    cfg := map[string]interface{}{
        "timeout": "1h",
    }

    fmt.Printf("%#v", opts)
    options.Resolve(opts, flagSet, cfg)
    fmt.Printf("%#v", opts)
}

Package options imports 7 packages (graph) and is imported by 204 packages. Updated 2019-03-03. Refresh now. Tools for package owners.