Skip to content

Instantly share code, notes, and snippets.

@ghigt
Created January 19, 2015 13:56
Show Gist options
  • Save ghigt/c5cb4c64c964710b9bed to your computer and use it in GitHub Desktop.
Save ghigt/c5cb4c64c964710b9bed to your computer and use it in GitHub Desktop.
Simple discovery app in go using consul
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"strconv"
"github.com/armon/consul-api"
)
// returns ip, port, error
func getAddress(a string) (string, string, error) {
c := consulapi.DefaultConfig()
c.Address = "consul:8500"
cl, e := consulapi.NewClient(c)
if e != nil {
return "", "", e
}
cs, e := cl.Agent().Services() //("app", "production", nil)
if e != nil {
return "", "", e
}
for _, ca := range cs {
if ca.Service == a {
log.Printf("Found %s:%s\n", ca.Service, strconv.Itoa(ca.Port))
return ca.Service, strconv.Itoa(ca.Port), nil
}
}
return "", "", fmt.Errorf("Nothing found")
}
func main() {
//ip, p, e := getAddress("app")
//if e != nil {
// log.Fatal(e)
//}
r, _ := http.Get("http://consul:8500/v1/catalog/service/app")
//r, e := http.Get(fmt.Sprint("http://", ip, ":", p))
//if e != nil {
// log.Fatal(e)
//}
defer r.Body.Close()
b, _ := ioutil.ReadAll(r.Body)
// catch err
fmt.Printf("%s\n", b)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment