Skip to content

Commit

Permalink
flags implementation and test
Browse files Browse the repository at this point in the history
  • Loading branch information
JeremyLoy committed Apr 5, 2019
1 parent 87c8001 commit 2f7f89f
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
18 changes: 18 additions & 0 deletions config.go
Expand Up @@ -23,6 +23,7 @@ package config

import (
"bufio"
"flag"
"fmt"
"os"
"reflect"
Expand Down Expand Up @@ -80,6 +81,23 @@ func (c *Builder) From(file string) *Builder {
return c
}

// FromFlags returns a new Builder, populated with the values from set flags.
// Flags must be parsed before calling this function.
func FromFlags() *Builder {
return newBuilder().FromFlags()
}

// FromFlags merges new values from set flag into the current config state, returning the Builder.
// Flags must be parsed before calling this function.
func (c *Builder) FromFlags() *Builder {
m := make(map[string]string)
flag.Visit(func(f *flag.Flag) {
m[strings.ToLower(f.Name)] = f.Value.String()
})
c.mergeConfig(m)
return c
}

// FromEnv returns a new Builder, populated with environment variables
func FromEnv() *Builder {
return newBuilder().FromEnv()
Expand Down
25 changes: 25 additions & 0 deletions example_test.go
@@ -1,6 +1,7 @@
package config_test

import (
"flag"
"fmt"
"io/ioutil"
"os"
Expand Down Expand Up @@ -66,3 +67,27 @@ func Example_fromFileWithOverride() {
// 5678
// true
}

func Example_flags() {
flag.String("databaseUrl", "", "")
flag.Int("port", 0, "")
// for slices, set the flag's type to the slices type
flag.String("subconfig__ipwhitelist", "", "")

flag.Set("databaseUrl", "db://")
flag.Set("port", "5678")
flag.Set("subconfig__ipwhitelist", "0.0.0.0 1.1.1.1 2.2.2.2")
flag.Parse()

var c MyConfig
config.FromFlags().To(&c)

fmt.Println(c.DatabaseURL)
fmt.Println(c.Port)
fmt.Println(c.SubConfig.IPWhitelist, len(c.SubConfig.IPWhitelist))

// Output:
// db://
// 5678
// [0.0.0.0 1.1.1.1 2.2.2.2] 3
}

0 comments on commit 2f7f89f

Please sign in to comment.