-
Notifications
You must be signed in to change notification settings - Fork 2
/
http_server.go
239 lines (198 loc) · 6.28 KB
/
http_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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
package main
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/url"
"path/filepath"
"unicode/utf8"
"github.com/pkg/errors"
"github.com/programmfabrik/apitest/internal/httpproxy"
"github.com/programmfabrik/apitest/pkg/lib/util"
"github.com/programmfabrik/golib"
"github.com/sirupsen/logrus"
)
// StartHttpServer start a simple http server that can server local test resources during the testsuite is running
func (ats *Suite) StartHttpServer() {
if ats.HttpServer == nil || ats.httpServer != nil {
return
}
// TODO: Can we remove idleConnsClosed, because it does not seem to do anything?
ats.idleConnsClosed = make(chan struct{})
mux := http.NewServeMux()
if ats.HttpServer.Dir == "" {
ats.httpServerDir = ats.manifestDir
} else if filepath.IsAbs(ats.HttpServer.Dir) {
ats.httpServerDir = filepath.Clean(ats.HttpServer.Dir)
} else {
ats.httpServerDir = filepath.Join(ats.manifestDir, ats.HttpServer.Dir)
}
mux.Handle("/", logH(ats.Config.LogShort, customStaticHandler(http.FileServer(http.Dir(ats.httpServerDir)))))
// bounce json response
mux.Handle("/bounce-json", logH(ats.Config.LogShort, cookiesMiddleware(http.HandlerFunc(bounceJSON))))
// bounce binary response with information in headers
mux.Handle("/bounce", logH(ats.Config.LogShort, http.HandlerFunc(bounceBinary)))
// bounce query response with query in response body, as it is
mux.Handle("/bounce-query", logH(ats.Config.LogShort, http.HandlerFunc(bounceQuery)))
// Start listening into proxy
ats.httpServerProxy = httpproxy.New(ats.HttpServer.Proxy)
ats.httpServerProxy.RegisterRoutes(mux, "/", ats.Config.LogShort)
// Register SMTP server query routes
if ats.smtpServer != nil {
ats.smtpServer.RegisterRoutes(mux, "/", ats.Config.LogShort)
}
ats.httpServer = &http.Server{
Addr: ats.HttpServer.Addr,
Handler: mux,
}
run := func() {
if !ats.Config.LogShort {
logrus.Infof("Starting HTTP Server: %s: %s", ats.HttpServer.Addr, ats.httpServerDir)
}
err := ats.httpServer.ListenAndServe()
if err != nil && !errors.Is(err, http.ErrServerClosed) {
// Error starting or closing listener:
logrus.Fatal("HTTP server ListenAndServe:", err)
}
}
if ats.HttpServer.Testmode {
// Run in foreground to test
logrus.Infof("Testmode for HTTP Server. Listening, not running tests...")
run()
} else {
go run()
util.WaitForTCP(ats.HttpServer.Addr)
}
}
// customStaticHandler can perform some operations before passing into final handler
func customStaticHandler(h http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
qs := r.URL.Query()
// We try not to include Content-Length header here
// As ultimately the default FileServer implementation will override all of them
// After diving into its code, the only way to avoid it is setting Content-Encoding header to some value
// In this case, 'identity', as per RFC 7231 / RFC 2616, means no compression or modification
noContentLengthHeader := qs.Get("no-content-length")
if noContentLengthHeader == "1" || noContentLengthHeader == "true" {
w.Header().Set("Content-Encoding", "identity")
}
h.ServeHTTP(w, r)
}
}
// StopHttpServer stop the http server that was started for this test suite
func (ats *Suite) StopHttpServer() {
if ats.HttpServer == nil || ats.httpServer == nil {
return
}
err := ats.httpServer.Shutdown(context.Background())
if err != nil {
// Error from closing listeners, or context timeout:
logrus.Errorf("HTTP server Shutdown: %v", err)
close(ats.idleConnsClosed)
<-ats.idleConnsClosed
} else if !ats.Config.LogShort {
logrus.Infof("Http Server stopped: %s", ats.httpServerDir)
}
ats.httpServer = nil
}
type ErrorResponse struct {
Error string `json:"error"`
Body any `json:"body,omitempty"`
}
func errorResponse(w http.ResponseWriter, statuscode int, err error, body any) {
resp := ErrorResponse{
Error: err.Error(),
Body: body,
}
b, err2 := golib.JsonBytesIndent(resp, "", " ")
if err2 != nil {
logrus.Debugf("Could not marshall error message %s: %s", err, err2)
http.Error(w, err2.Error(), 500)
}
http.Error(w, string(b), statuscode)
}
type BounceResponse struct {
Header http.Header `json:"header"`
QueryParams url.Values `json:"query_params"`
Body any `json:"body"`
}
// bounceJSON builds a json response including the header, query params and body of the request
func bounceJSON(w http.ResponseWriter, r *http.Request) {
var (
err error
bodyBytes []byte
bodyJSON, errorBody any
)
bodyBytes, err = io.ReadAll(r.Body)
if utf8.Valid(bodyBytes) {
if len(bodyBytes) > 0 {
errorBody = string(bodyBytes)
} else {
errorBody = nil
}
} else {
errorBody = bodyBytes
}
if err != nil {
errorResponse(w, 500, err, errorBody)
return
}
response := BounceResponse{
Header: r.Header,
QueryParams: r.URL.Query(),
}
if len(bodyBytes) > 0 {
err = json.Unmarshal(bodyBytes, &bodyJSON)
if err != nil {
errorResponse(w, 500, err, errorBody)
return
}
response.Body = bodyJSON
}
responseData, err := golib.JsonBytesIndent(response, "", " ")
if err != nil {
errorResponse(w, 500, err, response)
return
}
w.Write(responseData)
}
// bounceBinary returns the request in binary form
func bounceBinary(w http.ResponseWriter, r *http.Request) {
for param, values := range r.URL.Query() {
for _, value := range values {
w.Header().Add("X-Req-Query-"+param, value)
}
}
for param, values := range r.Header {
for _, value := range values {
w.Header().Add("X-Req-Header-"+param, value)
}
}
io.Copy(w, r.Body)
}
// bounceQuery returns the request query in response body
// for those cases where a body cannt be provided
func bounceQuery(w http.ResponseWriter, r *http.Request) {
rBody := bytes.NewBufferString(r.URL.RawQuery)
io.Copy(w, rBody)
}
func cookiesMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ckHeader := r.Header.Values("X-Test-Set-Cookies")
for _, ck := range ckHeader {
w.Header().Add("Set-Cookie", ck)
}
next.ServeHTTP(w, r)
})
}
func logH(skipLog bool, next http.Handler) http.Handler {
if skipLog {
return next
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// logrus.Debugf("http-server: %s: %q", r.Method, r.URL)
next.ServeHTTP(w, r)
})
}