Skip to content

Reload and AutoReload functions

Latest
Compare
Choose a tag to compare
@takattila takattila released this 02 Feb 19:05

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)

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)