/
server.go
189 lines (156 loc) · 4.05 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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
package server
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/go-logr/glogr"
"github.com/go-logr/logr"
"github.com/golang/glog"
"github.com/aka-bo/loqu/pkg/util"
)
// Options is used to configure the server
type Options struct {
ShutdownDelaySeconds int
ListenPort int
}
type clientInfo struct {
Address string `json:"address"`
}
type serverInfo struct {
Hostname string `json:"hostname"`
Started time.Time `json:""`
Stopping bool `json:"stopping"`
}
type requestInfo struct {
Path string `json:"path"`
Query string `json:"query,omitempty"`
Method string `json:"method"`
Body string `json:"body,omitempty"`
Headers http.Header `json:"headers"`
}
type response struct {
ID string `json:"id"`
Client clientInfo `json:"client"`
Server serverInfo `json:"server"`
Request requestInfo `json:"request"`
}
//Handler provides lifecycle hooks for an HttpHandler
type Handler interface {
Handle(http.ResponseWriter, *http.Request)
Start()
Stop()
}
type handlerMap map[string]Handler
func (h handlerMap) register(mux *http.ServeMux) {
for k, v := range h {
v.Start()
mux.Handle(k, requestIDHandler(v.Handle))
}
}
func requestIDHandler(h http.HandlerFunc) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h.ServeHTTP(w, r.WithContext(util.RequestContext(r)))
})
}
func (h handlerMap) shutdown() {
for _, v := range h {
v.Stop()
}
}
// Run the server, get them logs flowing
func Run(o *Options) {
logger := glogr.New().WithName("Server")
logger.Info("Run called", "options", o)
host, err := os.Hostname()
if err != nil {
panic(err)
}
shutdown := make(chan os.Signal, 1)
signal.Notify(shutdown, syscall.SIGTERM, syscall.SIGINT)
serverInfo := serverInfo{
Hostname: host,
Started: time.Now(),
}
handlers := handlerMap{
"/": &Default{serverInfo: serverInfo},
"/echo": &Echo{serverInfo: serverInfo, shutdownGracePeriodSeconds: o.ShutdownDelaySeconds - 1},
"/healthcheck": &HealthCheck{serverInfo: serverInfo},
}
mux := http.NewServeMux()
handlers.register(mux)
// mux.Handle("/demo", demoHandler())
addr := fmt.Sprintf(":%d", o.ListenPort)
server := &http.Server{
Addr: addr,
Handler: mux,
}
server.RegisterOnShutdown(func() {
logger.Info("Shutdown() called on http.Server")
})
go func() {
logger.Info("Starting server", "addr", addr)
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logger.Error(err, "server exited with error")
}
}()
sig := <-shutdown
logger.Info("signal received. signaling handlers and disabling keep-alives", "signal", sig.String())
server.SetKeepAlivesEnabled(false)
handlers.shutdown()
logger.Info("shutting down with delay", "delay", o.ShutdownDelaySeconds)
<-time.After(time.Duration(o.ShutdownDelaySeconds) * time.Second)
logger.Info("proceeding with shutdown")
logger.Info("commencing graceful shutdown of web server")
server.Shutdown(context.Background())
glog.Flush()
}
func buildResponse(server *serverInfo, r *http.Request) *response {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err)
}
return &response{
ID: util.GetRequestID(r),
Client: clientInfo{
Address: r.RemoteAddr,
},
Server: *server,
Request: requestInfo{
Body: string(body),
Path: r.URL.Path,
Query: r.URL.RawQuery,
Method: r.Method,
Headers: r.Header,
},
}
}
func marshal(v interface{}, pretty bool) ([]byte, error) {
if pretty {
return json.MarshalIndent(v, "", " ")
}
return json.Marshal(v)
}
func write(w http.ResponseWriter, status int, v []byte, logger logr.Logger) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if _, err := w.Write(v); err != nil {
logger.Error(err, "error writing data to the response writer")
}
}
func errorResponse(msg string) []byte {
v := &struct {
Message string
ErrorCode int
}{
Message: msg,
ErrorCode: http.StatusInternalServerError,
}
b, _ := json.Marshal(v)
return b
}