forked from influxdata/kapacitor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
131 lines (113 loc) · 2.37 KB
/
service.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
124
125
126
127
128
129
130
131
package httpd
import (
"crypto/tls"
"expvar"
"fmt"
"log"
"net"
"net/http"
"strings"
)
type Service struct {
ln net.Listener
addr string
https bool
cert string
err chan error
Handler *Handler
Logger *log.Logger
}
func NewService(c Config, l *log.Logger) *Service {
statMap := &expvar.Map{}
statMap.Init()
s := &Service{
addr: c.BindAddress,
https: c.HttpsEnabled,
cert: c.HttpsCertificate,
err: make(chan error),
Handler: NewHandler(
c.AuthEnabled,
c.LogEnabled,
c.WriteTracing,
statMap,
l,
),
Logger: l,
}
s.Handler.Logger = s.Logger
return s
}
// Open starts the service
func (s *Service) Open() error {
s.Logger.Println("I! Starting HTTP service")
s.Logger.Println("I! Authentication enabled:", s.Handler.requireAuthentication)
// Open listener.
if s.https {
cert, err := tls.LoadX509KeyPair(s.cert, s.cert)
if err != nil {
return err
}
listener, err := tls.Listen("tcp", s.addr, &tls.Config{
Certificates: []tls.Certificate{cert},
})
if err != nil {
return err
}
s.Logger.Println("I! Listening on HTTPS:", listener.Addr().String())
s.ln = listener
} else {
listener, err := net.Listen("tcp", s.addr)
if err != nil {
return err
}
s.Logger.Println("I! Listening on HTTP:", listener.Addr().String())
s.ln = listener
}
// Begin listening for requests in a separate goroutine.
go s.serve()
return nil
}
// Close closes the underlying listener.
func (s *Service) Close() error {
if s.ln != nil {
return s.ln.Close()
}
return nil
}
func (s *Service) Err() <-chan error {
return s.err
}
func (s *Service) Addr() net.Addr {
if s.ln != nil {
return s.ln.Addr()
}
return nil
}
func (s *Service) URL() string {
if s.ln != nil {
if s.https {
return "https://" + s.Addr().String()
}
return "http://" + s.Addr().String()
}
return ""
}
// serve serves the handler from the listener.
func (s *Service) serve() {
go func() {
err := http.Serve(s.ln, s.Handler)
// The listener was closed so exit
// See https://github.com/golang/go/issues/4373
if err != nil && !strings.Contains(err.Error(), "closed") {
s.err <- fmt.Errorf("listener failed: addr=%s, err=%s", s.Addr(), err)
} else {
s.err <- nil
}
}()
}
func (s *Service) AddRoutes(routes []Route) error {
return s.Handler.AddRoutes(routes)
}
func (s *Service) DelRoutes(routes []Route) {
s.Handler.DelRoutes(routes)
}