forked from flynn/flynn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
94 lines (83 loc) · 2.21 KB
/
server.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
package main
import (
"encoding/base64"
"flag"
"fmt"
"log"
"net/http"
"os"
"strings"
"github.com/flynn/flynn/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd"
"github.com/flynn/flynn/discoverd/client"
"github.com/flynn/flynn/router/types"
)
type Listener interface {
Start() error
Close() error
AddRoute(*router.Route) error
SetRoute(*router.Route) error
RemoveRoute(id string) error
Watcher
DataStoreReader
}
type Router struct {
HTTP Listener
TCP Listener
}
func (s *Router) ListenAndServe(quit <-chan struct{}) error {
if err := s.HTTP.Start(); err != nil {
return err
}
if err := s.TCP.Start(); err != nil {
return err
}
<-quit
// TODO: unregister from service discovery
s.HTTP.Close()
// TODO: wait for client connections to finish
return nil
}
func main() {
apiPort := os.Getenv("PORT")
if apiPort == "" {
apiPort = "5000"
}
var cookieKey *[32]byte
if key := os.Getenv("COOKIE_KEY"); key != "" {
res, err := base64.StdEncoding.DecodeString(key)
if err != nil {
log.Fatal("error decoding COOKIE_KEY:", err)
}
var k [32]byte
copy(k[:], res)
cookieKey = &k
}
httpAddr := flag.String("httpaddr", ":8080", "http listen address")
httpsAddr := flag.String("httpsaddr", ":4433", "https listen address")
tcpIP := flag.String("tcpip", "", "tcp router listen ip")
apiAddr := flag.String("apiaddr", ":"+apiPort, "api listen address")
flag.Parse()
// Will use DISCOVERD environment variable
d, err := discoverd.NewClient()
if err != nil {
log.Fatal(err)
}
if err := d.Register("router-api", *apiAddr); err != nil {
log.Fatal(err)
}
// Read etcd addresses from ETCD
etcdAddrs := strings.Split(os.Getenv("ETCD"), ",")
if len(etcdAddrs) == 1 && etcdAddrs[0] == "" {
if externalIP := os.Getenv("EXTERNAL_IP"); externalIP != "" {
etcdAddrs = []string{fmt.Sprintf("http://%s:4001", externalIP)}
} else {
etcdAddrs = nil
}
}
etcdc := etcd.NewClient(etcdAddrs)
var r Router
r.TCP = NewTCPListener(*tcpIP, 0, 0, NewEtcdDataStore(etcdc, "/router/tcp/"), d)
r.HTTP = NewHTTPListener(*httpAddr, *httpsAddr, cookieKey, NewEtcdDataStore(etcdc, "/router/http/"), d)
go func() { log.Fatal(r.ListenAndServe(nil)) }()
log.Fatal(http.ListenAndServe(*apiAddr, apiHandler(&r)))
}