-
Notifications
You must be signed in to change notification settings - Fork 9
/
main.go
103 lines (89 loc) · 2.33 KB
/
main.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package main
import (
"flag"
"fmt"
"log"
"net"
"net/http"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"github.com/magiconair/fabio-example/_third_party/github.com/hashicorp/consul/api"
)
func main() {
var addr, name, prefix string
flag.StringVar(&addr, "addr", "127.0.0.1:5000", "host:port of the service")
flag.StringVar(&name, "name", filepath.Base(os.Args[0]), "name of the service")
flag.StringVar(&prefix, "prefix", "", "comma-sep list of host/path prefixes to register")
flag.Parse()
if prefix == "" {
flag.Usage()
os.Exit(1)
}
// register prefixes
prefixes := strings.Split(prefix, ",")
for _, p := range prefixes {
http.HandleFunc(p, func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Serving %s from %s on %s\n", r.RequestURI, name, addr)
})
}
// start http server
go func() {
log.Printf("Listening on %s serving %s", addr, prefix)
if err := http.ListenAndServe(addr, nil); err != nil {
log.Fatal(err)
}
}()
// register consul health check endpoint
http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "OK")
})
// build urlprefix-host/path tag list
// e.g. urlprefix-/foo, urlprefix-/bar, ...
var tags []string
for _, p := range prefixes {
tags = append(tags, "urlprefix-"+p)
}
// get host and port as string/int
host, portstr, err := net.SplitHostPort(addr)
if err != nil {
log.Fatal(err)
}
port, err := strconv.Atoi(portstr)
if err != nil {
log.Fatal(err)
}
// register service with health check
serviceID := name + "-" + addr
service := &api.AgentServiceRegistration{
ID: serviceID,
Name: name,
Port: port,
Address: host,
Tags: tags,
Check: &api.AgentServiceCheck{
HTTP: "http://" + addr + "/health",
Interval: "1s",
Timeout: "1s",
},
}
client, err := api.NewClient(api.DefaultConfig())
if err != nil {
log.Fatal(err)
}
if err := client.Agent().ServiceRegister(service); err != nil {
log.Fatal(err)
}
log.Printf("Registered service %q in consul with tags %q", name, strings.Join(tags, ","))
// run until we get a signal
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt, os.Kill)
<-quit
// deregister service
if err := client.Agent().ServiceDeregister(serviceID); err != nil {
log.Fatal(err)
}
log.Printf("Deregistered service %q in consul", name)
}