-
Notifications
You must be signed in to change notification settings - Fork 0
/
backend.go
202 lines (168 loc) · 5.39 KB
/
backend.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
package playground
import (
"compress/flate"
"compress/gzip"
"context"
"errors"
"fmt"
"io"
"log/slog"
"maps"
"mime"
"net"
"net/http"
"strings"
"time"
)
var allowedMethods = map[string]struct{}{
http.MethodGet: {},
http.MethodPost: {},
http.MethodPut: {},
http.MethodPatch: {},
http.MethodDelete: {},
}
// maxBodyBytes is the accepted body size for a playground request.
const maxBodyBytes = 5 << 20 // 5 MB
type bodyFormatter interface {
format(input []byte, output io.Writer, indent string)
}
var (
textFormatter = &textFormatterImpl{}
xmlFormatter = &xmlFormatterImpl{}
jsonFormatter = &jsonFormatterImpl{}
htmlFormatter = &htmlFormatterImpl{}
)
var supportedMediaTypes = map[string]bodyFormatter{
"application/xml": xmlFormatter,
"application/problem+xml": xmlFormatter,
"application/json": jsonFormatter,
"application/problem+json": jsonFormatter,
"application/sql": textFormatter,
"application/yaml": textFormatter, // TODO: implement a YAML formatter
"text/xml": xmlFormatter,
"text/html": htmlFormatter,
}
var supportedEncodings = map[string]func(io.Reader) io.ReadCloser{
"gzip": func(r io.Reader) io.ReadCloser { out, _ := gzip.NewReader(r); return out },
"flate": flate.NewReader,
"compress": flate.NewReader,
}
var errNoRequest = errors.New("internal service error")
// backend sends an HTTP request to the target specified in the input request
// and returns a playgroundResponse with a formatted JSON body. If an error occurs during
// the request, it logs the error and returns nil.
func backend(ctx context.Context, in *request) (response *responseBuilder) {
client := &http.Client{
Timeout: 30 * time.Second,
Transport: &http.Transport{
DialContext: (&net.Dialer{
Timeout: 10 * time.Second,
KeepAlive: 10 * time.Second,
}).DialContext,
TLSHandshakeTimeout: 10 * time.Second,
},
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) >= 5 {
return http.ErrUseLastResponse
}
return nil
},
}
response = newResponseBuilder()
ctx, cancel := context.WithTimeout(ctx, client.Timeout)
defer cancel()
if _, ok := allowedMethods[in.method]; !ok {
response.WriteError(fmt.Errorf("method %s is not allowed", in.method))
response.DefaultHeaders()
return
}
var body io.Reader
if "" != in.body {
body = io.LimitReader(strings.NewReader(in.body), maxBodyBytes)
}
req, err := http.NewRequestWithContext(ctx, in.method, in.target.String(), body)
if nil != err {
slog.Error("http.NewRequestWithContext(...) failed",
slog.Group("error", slog.String("message", err.Error())),
slog.Group("request",
slog.String("method", in.method),
slog.String("target", in.target.String()),
slog.Int("n_headers", len(in.header)),
slog.String("headers", fmt.Sprintf("%v", in.header)),
),
)
response.WriteError(errNoRequest)
response.DefaultHeaders()
return
}
maps.Copy(req.Header, in.header)
res, err := client.Do(req)
if nil != err {
switch {
default:
slog.Error("client.Do(...) failed", slog.Group("error", slog.String("message", err.Error())))
response.WriteError(errNoRequest)
case errors.Is(err, context.DeadlineExceeded):
response.WriteError(errors.New("request timed out"))
case strings.Contains(err.Error(), "unsupported protocol scheme"):
response.WriteError(errors.New(strings.Split(err.Error(), ": ")[1]))
case strings.Contains(err.Error(), "no such host"):
response.WriteError(fmt.Errorf("could not connect to the server at %#q", in.target.String()))
}
response.DefaultHeaders()
return
}
response.SetStartLine(res.Proto, res.Status)
response.SetHeaders(res.Header)
var (
contentType = res.Header.Get("Content-Type")
mediatype, _, _ = mime.ParseMediaType(contentType)
formatter bodyFormatter
)
for mtype, f := range maps.All(supportedMediaTypes) {
if mediatype == mtype {
formatter = f
}
}
if nil == formatter {
if typ, _ := splitMediaType(mediatype); "text" != typ && "" != typ {
response.WriteError(fmt.Errorf("unsupported media type %#q", mediatype))
response.DefaultHeaders()
return
}
formatter = textFormatter
}
res.Body = http.MaxBytesReader(nil, res.Body, maxBodyBytes)
var bodyReader io.ReadCloser
contentEncoding := res.Header.Get("Content-Encoding")
for encoding, maker := range supportedEncodings {
if contentEncoding == encoding {
bodyReader = maker(res.Body)
}
}
if nil == bodyReader {
bodyReader = res.Body
}
defer bodyReader.Close()
result, err := io.ReadAll(bodyReader)
if nil != err {
switch {
default:
response.WriteError(errNoRequest)
slog.Error("io.ReadAll(...) failed", slog.Group("error", slog.String("message", err.Error())))
case strings.Contains(err.Error(), "request body too large"):
response.WriteError(fmt.Errorf("response body is too large"))
}
response.DefaultHeaders()
return
}
formatter.format(result, response, " ")
return response
}
// splitMediaType extracts the type and subtype from a MIME type.
func splitMediaType(v string) (typ string, subtype string) {
if parts := strings.Split(v, "/"); len(parts) == 2 {
return parts[0], strings.Split(parts[1], ";")[0]
}
return
}