Skip to content

Instantly share code, notes, and snippets.

@alex-leonhardt
Created August 11, 2017 16:37
Show Gist options
  • Save alex-leonhardt/4f6b7600aa017225d93695aa604a5cfd to your computer and use it in GitHub Desktop.
Save alex-leonhardt/4f6b7600aa017225d93695aa604a5cfd to your computer and use it in GitHub Desktop.
mini golang app to connect and return a message from consul kv
package main
import (
"encoding/json"
"net/http"
consul "github.com/hashicorp/consul/api"
)
func getKVdata() *consul.KVPair {
config := *consul.DefaultConfig()
// config.Address = "127.0.0.1:8500"
client, err := consul.NewClient(&config)
if err != nil {
panic(err)
}
kv := client.KV()
cqo := &consul.QueryOptions{}
cqo.AllowStale = true
// Lookup a kvpair
pair, _, err := kv.Get("appX/message", cqo)
if err != nil {
panic(err)
}
return pair
}
func HelloWorldHandler(w http.ResponseWriter, req *http.Request) {
w.Header().Add("Content-Type", "application/json")
kvp := getKVdata()
msg := map[string]string{}
msg["message"] = string(kvp.Value)
enc := json.NewEncoder(w)
enc.Encode(msg)
}
func main() {
http.HandleFunc("/", HelloWorldHandler)
http.ListenAndServe(":8080", nil)
}
@alex-leonhardt
Copy link
Author

there's intentionally no retry and no caching of values from the kv to test consul's stale data behaviour ;)

@alex-leonhardt
Copy link
Author

we can then see following in consul's log :

    2017/08/11 17:40:06 [DEBUG] http: Request GET /v1/kv/appX/message?stale= (139.211µs) from=127.0.0.1:60640
    2017/08/11 17:40:08 [DEBUG] http: Request GET /v1/kv/appX/message?stale= (169.881µs) from=127.0.0.1:60642

the ?stale= is important here

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