Skip to content

Instantly share code, notes, and snippets.

@developer-guy
Created December 8, 2020 13:35
Show Gist options
  • Save developer-guy/fc211e2d0e826c4c4efaef71353f2fbf to your computer and use it in GitHub Desktop.
Save developer-guy/fc211e2d0e826c4c4efaef71353f2fbf to your computer and use it in GitHub Desktop.
Read Consul K/V dynamically with config changes
package main
import (
"fmt"
"github.com/spf13/viper"
_ "github.com/spf13/viper/remote"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
v := viper.New()
_ = v.AddRemoteProvider("consul", "localhost:8500", "app/configs")
v.SetConfigType("json") // Need to explicitly set this to json
err := v.ReadRemoteConfig()
if err != nil {
panic(err)
}
sigChn := make(chan os.Signal, 1)
signal.Notify(sigChn, syscall.SIGTERM, syscall.SIGINT)
// open a goroutine to watch remote changes forever
go func() {
for {
// currently, only tested with etcd support
err := v.WatchRemoteConfig()
if err != nil {
fmt.Printf("unable to read remote config: %v", err)
continue
}
fmt.Println(v.Get("port")) // 8080
fmt.Println(v.Get("hostname")) // myhostname.com
time.Sleep(3 * time.Second)
}
}()
<-sigChn
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment