Skip to content

Instantly share code, notes, and snippets.

@RaccoonDev
Created March 20, 2018 20:29
Show Gist options
  • Save RaccoonDev/73d2fa8a34a747c5e3a0c4cba498ea5d to your computer and use it in GitHub Desktop.
Save RaccoonDev/73d2fa8a34a747c5e3a0c4cba498ea5d to your computer and use it in GitHub Desktop.
Blocking calls for changes in consul
package main
import (
"bufio"
"fmt"
"log"
"os"
"time"
consulapi "github.com/hashicorp/consul/api"
)
func main() {
c, err := consulapi.NewClient(consulapi.DefaultConfig())
if err != nil {
log.Panicln("Error creating consul client", err)
}
kv := c.KV()
ch := make(chan string)
go subscribeToChanges("loglevel", ch, kv)
go func() {
for data := range ch {
log.Println("Detected key change:", data)
}
}()
reader := bufio.NewReader(os.Stdin)
fmt.Println("Press ENTER to exit…")
reader.ReadString('\n')
}
func subscribeToChanges(key string, ch chan string, kv *consulapi.KV) {
currentIndex := uint64(0)
for {
pair, meta, err := kv.Get(key, &consulapi.QueryOptions{
WaitIndex: currentIndex,
})
if err != nil {
log.Panicln("Error read from KV", err.Error(), err)
}
if pair == nil || meta == nil {
// Query won’t be blocked if key not found
time.Sleep(1 * time.Second)
} else {
ch <- string(pair.Value)
currentIndex = meta.LastIndex
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment