Skip to content

Instantly share code, notes, and snippets.

@andrewmeissner
Created March 19, 2018 05:41
Show Gist options
  • Select an option

  • Save andrewmeissner/f9524709e0a15b336c174ddbaf82a2d3 to your computer and use it in GitHub Desktop.

Select an option

Save andrewmeissner/f9524709e0a15b336c174ddbaf82a2d3 to your computer and use it in GitHub Desktop.
Viper watching remote config backend Consul
package main
import (
"log"
"time"
"github.com/spf13/viper"
_ "github.com/spf13/viper/remote"
)
type config struct {
Context string `json:"context"`
Port int `json:"port"`
}
const (
backend = "consul"
backendAddr = "127.0.0.1:8500"
backendPath = "/config/test"
configType = "json"
)
func main() {
var conf config
err := viper.AddRemoteProvider(backend, backendAddr, backendPath)
if err != nil {
panic(err)
}
viper.SetConfigType(configType)
err = viper.ReadRemoteConfig()
if err != nil {
panic(err)
}
viper.Unmarshal(&conf)
log.Println(conf)
go func() {
for {
time.Sleep(5 * time.Second)
err := viper.WatchRemoteConfig()
if err != nil {
log.Printf("unable to read remote config: %v", err)
continue
}
viper.Unmarshal(&conf)
log.Println(conf)
}
}()
for {
// simulate a long running process
}
}
@tranphuoctien
Copy link

How to get data with token?

Copy link

ghost commented Jul 8, 2021

@tranphuoctien You need to manage that through crypt by setting environment variable CONSUL_HTTP_TOKEN

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment