/
server.go
123 lines (98 loc) · 2.34 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package api
import "github.com/cloudtask/cloudtask-agent/api/middleware"
import (
"crypto/tls"
"fmt"
"net"
"net/http"
"strings"
)
type Dispatcher struct {
handler http.Handler
}
func (dispatcher *Dispatcher) SetHandler(handler http.Handler) {
dispatcher.handler = handler
}
func (dispatcher *Dispatcher) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if dispatcher.handler == nil {
httpError(w, "API Dispatcher Invalid.", http.StatusInternalServerError)
return
}
handler := middleware.Logger(dispatcher.handler)
handler.ServeHTTP(w, r)
}
var store = make(Store)
type Server struct {
hosts []string
tlsConfig *tls.Config
dispatcher *Dispatcher
}
func NewServer(hosts []string, enableCors bool, tlsConfig *tls.Config) *Server {
router := NewRouter(enableCors, store)
return &Server{
hosts: hosts,
tlsConfig: tlsConfig,
dispatcher: &Dispatcher{
handler: router,
},
}
}
func RegisterStore(name string, value interface{}) {
store[name] = value
}
func (server *Server) ListenHosts() []string {
return server.hosts
}
func (server *Server) SetHandler(handler http.Handler) {
server.dispatcher.SetHandler(handler)
}
func (server *Server) Startup() error {
errorsCh := make(chan error, len(server.hosts))
for _, host := range server.hosts {
protoAddrParts := strings.SplitN(host, "://", 2)
if len(protoAddrParts) == 1 {
protoAddrParts = append([]string{"tcp"}, protoAddrParts...)
}
go func() {
var (
err error
l net.Listener
s = http.Server{
Addr: protoAddrParts[1],
Handler: server.dispatcher,
}
)
switch protoAddrParts[0] {
case "unix":
l, err = newUnixListener(protoAddrParts[1], server.tlsConfig)
case "tcp":
l, err = newListener("tcp", protoAddrParts[1], server.tlsConfig)
default:
err = fmt.Errorf("API UnSupported Protocol:%q", protoAddrParts[0])
}
if err != nil {
errorsCh <- err
} else {
errorsCh <- s.Serve(l)
}
}()
}
for i := 0; i < len(server.hosts); i++ {
err := <-errorsCh
if err != nil {
return err
}
}
return nil
}
func newListener(proto string, addr string, tlsConfig *tls.Config) (net.Listener, error) {
l, err := net.Listen(proto, addr)
if err != nil {
return nil, err
}
if tlsConfig != nil {
tlsConfig.NextProtos = []string{"http/1.1"}
l = tls.NewListener(l, tlsConfig)
}
return l, nil
}