This repository has been archived by the owner on May 14, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 56
/
discovery.go
90 lines (69 loc) · 1.94 KB
/
discovery.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
package main
import (
"context"
"fmt"
"log"
"net/http"
"net/url"
"os"
handling "github.com/coreos/discovery.etcd.io/http"
"github.com/coreos/go-systemd/activation"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)
func fail(err string) {
log.Print(err)
pflag.PrintDefaults()
os.Exit(2) // default go flag error code
}
func mustHostOnlyURL(givenUrl string) string {
u, err := url.Parse(givenUrl)
if err != nil {
fail(fmt.Sprintf("Invalid url given: %v", err))
}
if len(u.Path) != 0 && u.Path != "/" {
fail(fmt.Sprintf("Expected url without path (%v)", u.Path))
}
if u.RawQuery != "" {
fail(fmt.Sprintf("Expected url without query (?%v)", u.RawQuery))
}
if u.Fragment != "" {
fail(fmt.Sprintf("Expected url without fragment (%v)", u.Fragment))
}
if u.Host == "" {
fail(fmt.Sprint("Expected hostname (none given)"))
}
return u.Scheme + "://" + u.Host
}
func init() {
viper.SetEnvPrefix("disc")
viper.AutomaticEnv()
pflag.StringP("etcd", "e", "http://127.0.0.1:2379", "etcd endpoint location")
pflag.StringP("host", "h", "https://discovery.etcd.io", "discovery url prefix")
pflag.StringP("addr", "a", ":8087", "web service address")
viper.BindPFlag("etcd", pflag.Lookup("etcd"))
viper.BindPFlag("host", pflag.Lookup("host"))
viper.BindPFlag("addr", pflag.Lookup("addr"))
pflag.Parse()
}
func main() {
log.SetFlags(0)
etcdHost := mustHostOnlyURL(viper.GetString("etcd"))
discHost := mustHostOnlyURL(viper.GetString("host"))
webAddr := viper.GetString("addr")
handling.Setup(context.Background(), etcdHost, discHost)
log.Printf("discovery server started with etcd %q and host %q", etcdHost, discHost)
log.Printf("discovery serving on %s", webAddr)
err := http.ListenAndServe(webAddr, nil)
if err != nil {
panic(err)
}
listeners, err := activation.Listeners()
if err != nil {
panic(err)
}
if len(listeners) != 1 {
panic("Unexpected number of socket activation fds")
}
http.Serve(listeners[0], nil)
}