settings

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Feb 2, 2020 License: MIT Imports: 14 Imported by: 0

README

GO - Settings Manager

Test Coverage Status GOdoc Version

This package was made, to easily get needed settings from a file.

  • Supported file types are: 'json', and 'yaml'.
  • The configuration keys are case insensitive.

This package uses github.com/spf13/viper

Table of Contents

Example usage

Initialization

Initialize settings from a file or from multiple files under given directory.

sm := settings.New("./example/settings/config.yaml")

// ... or by passing directory path:

sm := settings.New("./example/settings")

Back to top

Merge configuration with other settings file

Merge initialized settings with a given file or directory.

sm := settings.New("./example/settings/config.yaml").
	Merge("./example/settings/test.yaml")

Back to top

Initialize settings from a given content

Initialize settings from a given content.

content := `
other:
  content:
    int: 1
    string: 'text'
    bool: true
`
sm := settings.NewFromContent(content)

Back to top

Get all keys from the settings

Return all keys holding a value, regardless of where they are set.

content := `
other:
  content:
    int: 1
    string: 'text'
    bool: true
`
sm := settings.NewFromContent(content)
keys, err := sm.GetAllKeys()
if err != nil {
    log.Fatal(err)
}

// Output:
// 2020/01/29 19:09:52 keys [other content.int content.string content.bool]
log.Println("keys", keys)

Back to top

Get all settings

Merge all Settings and return them.

content := `
other:
  content:
    int: 1
    string: 'text'
    bool: true
`
sm := settings.NewFromContent(content)
allSettings, err := sm.GetAllSettings()
if err != nil {
    log.Fatal(err)
}

// Output:
// 2020/01/29 19:11:58 allSettings map[content:map[bool:true int:1 string:text]]
log.Println("allSettings", allSettings)

Back to top

Add a sub tree

Returning a new settings instance representing a sub tree of this instance. SubTree is case-insensitive for a key.

var content = `
a:
  b:
    c:
      value: 1
`

sm := settings.NewFromContent(content)

sm = sm.SubTree("a.b")

intValue, err := sm.GetInt("c.value")
if err != nil {
    log.Fatal(err)
}

// Output:
// 2020/02/02 15:52:55 allSettings 1
log.Println("allSettings", intValue)

Back to top

Type assertions
sm := settings.New("./example/settings/settings.yaml")

interfaceKey, err := sm.Get("interface.key")
boolKey, err := sm.GetBool("bool.key")
float64Key, err := sm.GetFloat64("float64.key")
intKey, err := sm.GetInt("int.key")
stringKey, err := sm.GetString("string.key")
intSliceKey, err := sm.GetIntSlice("int.slice.key")
stringMapKey, err := sm.GetStringMap("string.map.key")
stringMapKey, err := sm.GetStringMapString("string.map.key")
stringSliceKey, err := sm.GetStringSlice("string.slice.key")
timeKey, err := sm.GetTime("time.key")
timeDurationKey, err := sm.GetDuration("time.duration.key")

Back to top

Reload the settings data manually

Re-read the settings data by calling the Reload function.

content := `
config:
  config_key:  config_value`

err := ioutil.WriteFile("./example/settings/example_config.yaml", []byte(content), os.ModePerm)
if err != nil {
    log.Fatal(err)
}

sm := settings.New("./example/settings/example_config.yaml")

v, err := sm.Get("config.config_key")
if err != nil {
    log.Fatal(err)
}

// Output:
// 2020/02/02 15:31:58 config_value
log.Println(v)

content = strings.ReplaceAll(content, "config_key:  config_value", "foo:  bar")
err = ioutil.WriteFile("./example/settings/example_config.yaml", []byte(content), os.ModePerm)
if err != nil {
    log.Fatal(err)
}

// Reload the configuration ...
sm.Reload()

v, err = sm.Get("config.foo")
if err != nil {
    log.Fatal(err)
}

// Output:
// 2020/02/02 15:31:58 bar
log.Println(v)

Back to top

Automatic reload the settings data in the background

AutoReload is watching for settings file changes in the background and reloads configuration if needed.

content := `
config:
  config_key:  config_value`

err := ioutil.WriteFile("./example/settings/example_config.yaml", []byte(content), os.ModePerm)
if err != nil {
    log.Fatal(err)
}

sm := settings.New("./example/settings/example_config.yaml")

// Activate the automatic reload function ...
sm.AutoReload()

v, err := sm.Get("config.config_key")
if err != nil {
    log.Fatal(err)
}

// Output:
// 2020/02/02 15:42:49 config_value
log.Println(v)

content = strings.ReplaceAll(content, "config_key:  config_value", "foo:  bar")
err = ioutil.WriteFile("./example/settings/example_config.yaml", []byte(content), os.ModePerm)
if err != nil {
    log.Fatal(err)
}

time.Sleep(5 * time.Millisecond)

v, err = sm.Get("config.foo")
if err != nil {
    log.Fatal(err)
}

// Output:
// 2020/02/02 15:42:49 settings.AutoReload settings reloaded
// 2020/02/02 15:42:49 bar
log.Println(v)

content = strings.ReplaceAll(content, "foo:  bar", "config_key:  config_value")
err = ioutil.WriteFile("./example/settings/example_config.yaml", []byte(content), os.ModePerm)
if err != nil {
    log.Fatal(err)
}

time.Sleep(5 * time.Millisecond)

v, err = sm.Get("config.config_key")
if err != nil {
    log.Fatal(err)
}

// Output:
// 2020/02/02 15:42:49 settings.AutoReload settings reloaded
// 2020/02/02 15:42:49 config_value
log.Println(v)

Back to top

Documentation

Overview

This package was made, to easily get needed settings from a file. Supported file types are: json and yaml.

This package uses https://github.com/spf13/viper: Copyright © 2014 Steve Francia <spf@spf13.com>.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Settings

type Settings struct {
	Data  *viper.Viper
	Error error
	// contains filtered or unexported fields
}

func New

func New(settingsFile string) *Settings

New initializes settings from a file or from multiple files under given directory.

Example
file := "example_config.yaml"
content := "config:\n  key:  value"

err := ioutil.WriteFile(file, []byte(content), os.ModePerm)
if err != nil {
	log.Fatal(err)
}

sm := settings.New(file)

AllSettings, err := sm.GetAllSettings()
if err != nil {
	log.Fatal(err)
}

fmt.Println(AllSettings)
Output:

map[config:map[key:value]]

func NewFromContent added in v1.0.1

func NewFromContent(content string) *Settings

NewFromContent initializes settings from a given content.

Example
content := "config:\n  key:  value"

sm := settings.NewFromContent(content)

AllSettings, err := sm.GetAllSettings()
if err != nil {
	log.Fatal(err)
}

fmt.Println(AllSettings)
Output:

map[config:map[key:value]]

func (*Settings) AutoReload added in v1.0.1

func (s *Settings) AutoReload()

AutoReload watching for settings file changes in the background and reloads configuration if needed.

Example
file := "example_config.yaml"
content := "config:\n  key:  value"

// Save content
err := ioutil.WriteFile(file, []byte(content), os.ModePerm)
if err != nil {
	log.Fatal(err)
}

sm := settings.New(file)

// Activate the automatic reload function ...
sm.AutoReload()

v, err := sm.Get("config.key")
if err != nil {
	log.Fatal(err)
}

fmt.Println(v)

// First update of the content
content = strings.ReplaceAll(content, "key:  value", "foo:  bar")
err = ioutil.WriteFile(file, []byte(content), os.ModePerm)
if err != nil {
	log.Fatal(err)
}

time.Sleep(5 * time.Millisecond)

v, err = sm.Get("config.foo")
if err != nil {
	log.Fatal(err)
}

fmt.Println(v)

// Second update of the content
content = strings.ReplaceAll(content, "foo:  bar", "key:  value")
err = ioutil.WriteFile(file, []byte(content), os.ModePerm)
if err != nil {
	log.Fatal(err)
}

time.Sleep(5 * time.Millisecond)

v, err = sm.Get("config.key")
if err != nil {
	log.Fatal(err)
}

fmt.Println(v)
Output:

value
bar
value

func (*Settings) Get

func (s *Settings) Get(key string) (interface{}, error)

Get can retrieve any value given the key to use. Get is case-insensitive for a key. Get has the behavior of returning the value associated with the first place from where it is set. Settings will checkErrors in the following order: override, flag, env, config file, key/value store, default

Get returns an interface. For a specific value use one of the Get____ methods.

Example
file := "example_app1.yaml"
content := `{ "app": { "string": "value", "int": 1 } }`

err := ioutil.WriteFile(file, []byte(content), os.ModePerm)
if err != nil {
	log.Fatal(err)
}

sm := settings.New(file)

v, err := sm.Get("app.string")
if err != nil {
	log.Fatal(err)
}

fmt.Println(v)

v, err = sm.Get("app.int")
if err != nil {
	log.Fatal(err)
}

fmt.Println(v)
Output:

value
1

func (*Settings) GetAllKeys

func (s *Settings) GetAllKeys() ([]string, error)

GetAllKeys returns all keys holding a value, regardless of where they are set. Nested keys are returned with a v.key delimiter separator

Example
content := "config:\n  key:  value"

sm := settings.NewFromContent(content)
keys, err := sm.GetAllKeys()
if err != nil {
	log.Fatal(err)
}

fmt.Println(keys)
Output:

[config.key]

func (*Settings) GetAllSettings

func (s *Settings) GetAllSettings() (map[string]interface{}, error)

GetAllSettings merges all Settings and returns them as a map[string]interface{}.

Example
content := "config:\n  key:  value"

sm := settings.NewFromContent(content)
AllSettings, err := sm.GetAllSettings()
if err != nil {
	log.Fatal(err)
}

fmt.Println(AllSettings)
Output:

map[config:map[key:value]]

func (*Settings) GetBool

func (s *Settings) GetBool(key string) (bool, error)

GetBool returns the value associated with the key as a boolean.

Example
file := "example_app1.yaml"
content := "app:\n  bool:  true"

err := ioutil.WriteFile(file, []byte(content), os.ModePerm)
if err != nil {
	log.Fatal(err)
}

sm := settings.New(file)

v, err := sm.GetBool("app.bool")
if err != nil {
	log.Fatal(err)
}

fmt.Printf("value: %t, type: %T\n", v, v)
Output:

value: true, type: bool

func (*Settings) GetDuration

func (s *Settings) GetDuration(key string) (time.Duration, error)

GetDuration returns the value associated with the key as a duration.

Example
file := "example_app1.yaml"
content := "time:\n  duration: 10"

err := ioutil.WriteFile(file, []byte(content), os.ModePerm)
if err != nil {
	log.Fatal(err)
}

sm := settings.New(file)

v, err := sm.GetDuration("time.duration")
if err != nil {
	log.Fatal(err)
}

fmt.Printf("time.duration: %d, type: %T\n", v, v)
Output:

time.duration: 10, type: time.Duration

func (*Settings) GetFloat64

func (s *Settings) GetFloat64(key string) (float64, error)

GetFloat64 returns the value associated with the key as a float64.

Example
file := "example_app1.yaml"
content := "app:\n  float64:  123131232132113211564564456"

err := ioutil.WriteFile(file, []byte(content), os.ModePerm)
if err != nil {
	log.Fatal(err)
}

sm := settings.New(file)

v, err := sm.GetFloat64("app.float64")
if err != nil {
	log.Fatal(err)
}

fmt.Printf("value: %b, type: %T\n", v, v)
Output:

value: 7167181007803488p+34, type: float64

func (*Settings) GetInt

func (s *Settings) GetInt(key string) (int, error)

GetInt returns the value associated with the key as an integer.

Example
file := "example_app1.yaml"
content := "app:\n  int:  100"

err := ioutil.WriteFile(file, []byte(content), os.ModePerm)
if err != nil {
	log.Fatal(err)
}

sm := settings.New(file)

v, err := sm.GetInt("app.int")
if err != nil {
	log.Fatal(err)
}

fmt.Printf("value: %d, type: %T\n", v, v)
Output:

value: 100, type: int

func (*Settings) GetIntSlice

func (s *Settings) GetIntSlice(key string) ([]int, error)

GetIntSlice returns the value associated with the key as a slice of int values.

Example
file := "example_app1.yaml"
content := `{ "app": { "int_slice": [ 1, 2 ] } }`

err := ioutil.WriteFile(file, []byte(content), os.ModePerm)
if err != nil {
	log.Fatal(err)
}

sm := settings.New(file)

v, err := sm.GetIntSlice("app.int_slice")
if err != nil {
	log.Fatal(err)
}

fmt.Printf("value: %d, type: %T\n", v, v)
Output:

value: [1 2], type: []int

func (*Settings) GetSettingsFileNames added in v1.0.1

func (s *Settings) GetSettingsFileNames() ([]string, error)

GetSettingsFileNames returns the name of all settings files, whence settings manager was initialized.

Example
file1 := "example_app1.yaml"
content1 := "app1:\n  key:  value1"

err := ioutil.WriteFile(file1, []byte(content1), os.ModePerm)
if err != nil {
	log.Fatal(err)
}

file2 := "example_app2.yaml"
content2 := "app2:\n  key:  value2"

err = ioutil.WriteFile(file2, []byte(content2), os.ModePerm)
if err != nil {
	log.Fatal(err)
}

sm := settings.New(file1).Merge(file2)

files, err := sm.GetSettingsFileNames()
if err != nil {
	log.Fatal(err)
}

fmt.Println(files)
Output:

[example_app1.yaml example_app2.yaml]

func (*Settings) GetString

func (s *Settings) GetString(key string) (string, error)

GetString returns the value associated with the key as a string.

Example
file := "example_app1.yaml"
content := "app:\n  string: some text"

err := ioutil.WriteFile(file, []byte(content), os.ModePerm)
if err != nil {
	log.Fatal(err)
}

sm := settings.New(file)

v, err := sm.GetString("app.string")
if err != nil {
	log.Fatal(err)
}

fmt.Printf("value: %s, type: %T\n", v, v)
Output:

value: some text, type: string

func (*Settings) GetStringMap

func (s *Settings) GetStringMap(key string) (map[string]interface{}, error)

GetStringMap returns the value associated with the key as a map of interfaces.

Example
file := "example_app1.yaml"
content := `{ "app": { "string_map": { "one": "value1", "two": "value2" } } }`

err := ioutil.WriteFile(file, []byte(content), os.ModePerm)
if err != nil {
	log.Fatal(err)
}

sm := settings.New(file)

v, err := sm.GetStringMap("app.string_map")
if err != nil {
	log.Fatal(err)
}

fmt.Printf("type: %T\n", v)
fmt.Printf("app.string_map.one: %s\n", v["one"])
fmt.Printf("app.string_map.two: %s\n", v["two"])
Output:

type: map[string]interface {}
app.string_map.one: value1
app.string_map.two: value2

func (*Settings) GetStringMapString

func (s *Settings) GetStringMapString(key string) (map[string]string, error)

GetStringMapString returns the value associated with the key as a map of strings.

Example
file := "example_app1.yaml"
content := `{ "app": { "string_map": { "one": "value1", "two": "value2" } } }`

err := ioutil.WriteFile(file, []byte(content), os.ModePerm)
if err != nil {
	log.Fatal(err)
}

sm := settings.New(file)

v, err := sm.GetStringMapString("app.string_map")
if err != nil {
	log.Fatal(err)
}

fmt.Printf("type: %T\n", v)
fmt.Printf("app.string_map.one: %s\n", v["one"])
fmt.Printf("app.string_map.two: %s\n", v["two"])
Output:

type: map[string]string
app.string_map.one: value1
app.string_map.two: value2

func (*Settings) GetStringSlice

func (s *Settings) GetStringSlice(key string) ([]string, error)

GetStringSlice returns the value associated with the key as a slice of strings.

Example
file := "example_app1.yaml"
content := `{ "app": { "string_slice": [ "value1", "value2" ] } }`

err := ioutil.WriteFile(file, []byte(content), os.ModePerm)
if err != nil {
	log.Fatal(err)
}

sm := settings.New(file)

v, err := sm.GetStringSlice("app.string_slice")
if err != nil {
	log.Fatal(err)
}

fmt.Printf("app.string_slice: %s, type: %T\n", v, v)
Output:

app.string_slice: [value1 value2], type: []string

func (*Settings) GetTime

func (s *Settings) GetTime(key string) (time.Time, error)

GetTime returns the value associated with the key as time.

Example
file := "example_app1.yaml"
content := "time:\n  seconds: 10"

err := ioutil.WriteFile(file, []byte(content), os.ModePerm)
if err != nil {
	log.Fatal(err)
}

sm := settings.New(file)

v, err := sm.GetTime("time.seconds")
if err != nil {
	log.Fatal(err)
}

fmt.Printf("time.seconds: %d, type: %T\n", v.Second(), v)
Output:

time.seconds: 10, type: time.Time

func (*Settings) IsSet

func (s *Settings) IsSet(key string) (bool, error)

IsSet checks to see if the key has been set in any of the Data locations. IsSet is case-insensitive for a key.

Example
file := "example_app1.yaml"
content := "app1:\n  key: value"

err := ioutil.WriteFile(file, []byte(content), os.ModePerm)
if err != nil {
	log.Fatal(err)
}

sm := settings.New(file)

isSet, err := sm.IsSet("app1.key")
if err != nil {
	log.Fatal(err)
}

fmt.Printf("app1.key: %t, type: %T\n", isSet, isSet)

isSet, err = sm.IsSet("app2.key")
if err != nil {
	log.Fatal(err)
}

fmt.Printf("app2.key: %t, type: %T\n", isSet, isSet)
Output:

app1.key: true, type: bool
app2.key: false, type: bool

func (*Settings) Merge

func (s *Settings) Merge(settingsFile string) *Settings

Merge merges initialized settings with a given file or directory.

Example
file1 := "example_app1.yaml"
content1 := "app1:\n  key:  value1"

err := ioutil.WriteFile(file1, []byte(content1), os.ModePerm)
if err != nil {
	log.Fatal(err)
}

file2 := "example_app2.yaml"
content2 := "app2:\n  key:  value2"

err = ioutil.WriteFile(file2, []byte(content2), os.ModePerm)
if err != nil {
	log.Fatal(err)
}

sm := settings.New(file1).Merge(file2)

k, err := sm.Get("app1.key")
if err != nil {
	log.Fatal(err)
}

fmt.Println(k)

k, err = sm.Get("app2.key")
if err != nil {
	log.Fatal(err)
}

fmt.Println(k)
Output:

value1
value2

func (*Settings) Reload added in v1.0.1

func (s *Settings) Reload()

Reload once it's called, will re-read the settings data.

Example
file := "example_config.yaml"
content := "config:\n  key:  value"

err := ioutil.WriteFile(file, []byte(content), os.ModePerm)
if err != nil {
	log.Fatal(err)
}

sm := settings.New(file)

v, err := sm.Get("config.key")
if err != nil {
	log.Fatal(err)
}

fmt.Println(v)

content = strings.ReplaceAll(content, "key:  value", "foo:  bar")
err = ioutil.WriteFile(file, []byte(content), os.ModePerm)
if err != nil {
	log.Fatal(err)
}

// Reload the configuration ...
sm.Reload()

v, err = sm.Get("config.foo")
if err != nil {
	log.Fatal(err)
}

fmt.Println(v)
Output:

value
bar

func (*Settings) SubTree added in v1.0.1

func (s *Settings) SubTree(prefix string) *Settings

SubTree returns a new settings instance representing a sub tree of this instance. SubTree is case-insensitive for a key.

Example
content := `{ "config": { "sub": { "tree": "value" } } }`

sm := settings.NewFromContent(content)
sm = sm.SubTree("config.sub")

v, err := sm.Get("tree")
if err != nil {
	log.Fatal(err)
}

fmt.Println(v)
Output:

value

Jump to

Keyboard shortcuts

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