-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
95 lines (88 loc) · 2.38 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
package main
import (
"crypto/tls"
"flag"
"io/ioutil"
"log"
"net"
"net/http"
"strings"
"time"
"github.com/coreos/etcd/client"
"github.com/facebookgo/grace/gracehttp"
)
var (
index string
html []byte
folder string
endpoints []string
httpAddr string
httpsAddr string
sslCert string
sslKey string
store Store
)
func redirect(port string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hostport := r.Context().Value(http.LocalAddrContextKey).(net.Addr).String()
host, _, _ := net.SplitHostPort(hostport)
r.URL.Scheme = "https"
r.URL.Host = net.JoinHostPort(host, port)
http.Redirect(w, r, r.URL.String(), http.StatusTemporaryRedirect)
})
}
func init() {
var list string
flag.StringVar(&index, "index", "html/index.html", "index to serve on root")
flag.StringVar(&folder, "folder", "/", "etcd folder to store keys")
flag.StringVar(&list, "endpoints", "http://127.0.0.1:2379", "comma-separated list of etcd endpoints")
flag.StringVar(&httpAddr, "http", ":8080", "listen http protocol on")
flag.StringVar(&httpsAddr, "https", "", "listen https protocol on (default disabled)")
flag.StringVar(&sslCert, "ssl-cert", "cert/localhost.crt", "ssl certificate")
flag.StringVar(&sslKey, "ssl-key", "cert/localhost.key", "ssl certificate key")
flag.Parse()
endpoints = strings.Split(list, ",")
}
func main() {
var err error
html, err = ioutil.ReadFile(index)
if err != nil {
log.Fatal(err)
}
cfg := client.Config{
Endpoints: endpoints,
Transport: client.DefaultTransport,
HeaderTimeoutPerRequest: time.Second,
}
c, err := client.New(cfg)
if err != nil {
log.Fatal(err)
}
store = NewEtcdStore(folder, c)
servers := []*http.Server{}
if httpsAddr == "" {
servers = append(servers, &http.Server{
Addr: httpAddr,
Handler: handler(),
})
} else {
_, httpsPort, err := net.SplitHostPort(httpsAddr)
if err != nil {
log.Fatal("malformed address", httpAddr)
}
cer, err := tls.LoadX509KeyPair(sslCert, sslKey)
if err != nil {
log.Fatal("error load certificates")
}
servers = append(servers, &http.Server{
Addr: httpAddr,
Handler: redirect(httpsPort),
})
servers = append(servers, &http.Server{
Addr: httpsAddr,
Handler: handler(),
TLSConfig: &tls.Config{Certificates: []tls.Certificate{cer}},
})
}
log.Fatal(gracehttp.Serve(servers...))
}