-
Notifications
You must be signed in to change notification settings - Fork 18
/
demo.go
78 lines (60 loc) · 1.45 KB
/
demo.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main
import (
"encoding/json"
"flag"
"fmt"
"github.com/benschw/dns-clb-go/clb"
"io/ioutil"
"log"
"net/http"
"os"
)
func getAddress(svcName string) (string, error) {
c := clb.NewClb("127.0.0.1", "8600", clb.Random)
srvRecord := svcName + ".service.consul"
address, err := c.GetAddress(srvRecord)
if err != nil {
return "", err
}
return address.String(), nil
}
func foo(w http.ResponseWriter, req *http.Request) {
name, _ := os.Hostname()
fmt.Fprintf(w, "{\"Name\": \"%s\"}", name)
}
type FooName struct {
Name string
}
func demo(w http.ResponseWriter, req *http.Request) {
addStr, err := getAddress("my-svc")
if err != nil {
log.Fatal(err)
}
url := "http://" + addStr + "/foo"
res, err := http.Get(url)
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Fatal(err)
}
var data FooName
err = json.Unmarshal(body, &data)
if err != nil {
log.Fatal(err)
}
fmt.Fprintf(w, "Discovered Address: '%s'\nService Response: Host Name: '%s'", addStr, data.Name)
}
var addr = flag.String("addr", ":8080", "http service address") // Q=17, R=18
var consulAddr = *flag.String("consul-addr", "localhost:8500", "consul address") // Q=17, R=18
func main() {
flag.Parse()
http.Handle("/foo", http.HandlerFunc(foo))
http.Handle("/demo", http.HandlerFunc(demo))
err := http.ListenAndServe(*addr, nil)
if err != nil {
log.Fatal("ListenAndServe:", err)
}
}