Created
August 11, 2017 16:37
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
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
there's intentionally no retry and no caching of values from the kv to test consul's stale data behaviour ;)