-
Notifications
You must be signed in to change notification settings - Fork 0
/
glhf.go
590 lines (538 loc) · 15.2 KB
/
glhf.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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
package glhf
import (
"encoding/json"
"io"
"net/http"
"google.golang.org/protobuf/proto"
)
// Body is the request's body.
type Body any
// EmptyBody represents an empty http request body
type EmptyBody struct{}
const (
// ContentType header constant.
ContentType = "Content-Type"
Accept = "Accept"
// ContentJSON header value for JSON data.
ContentJSON = "application/json"
// ContentProto header value for proto buff
ContentProto = "application/proto"
// TODO :: Add additional content type support
// ContentBinary header value for binary data.
ContentBinary = "application/octet-stream"
// ContentHTML header value for HTML data.
ContentHTML = "text/html"
// ContentText header value for Text data.
ContentText = "text/plain"
// ContentXHTML header value for XHTML data.
ContentXHTML = "application/xhtml+xml"
// ContentXML header value for XML data.
ContentXML = "text/xml"
)
// HandleFunc responds to an HTTP request.
// I and O represent the request body or response body.
type HandleFunc[I Body, O Body] func(*Request[I], *Response[O])
// MarshalFunc defines how a body should be marshaled into bytes
type MarshalFunc[I Body] func(I) ([]byte, error)
// Delete deletes the specified resource. The underlying request body is optional.
func Delete[I Body, O Body](fn HandleFunc[I, O], options ...Options) http.HandlerFunc {
opts := defaultOptions()
for _, opt := range options {
opt.Apply(opts)
}
return func(w http.ResponseWriter, r *http.Request) {
var errResp *errorResponse
if r.Method != http.MethodDelete {
errResp = &errorResponse{
Code: http.StatusMethodNotAllowed,
Message: "invalid method used, expected DELETE found " + r.Method,
}
}
var requestBody I
// check for request body
if r.Body != nil || r.ContentLength >= 0 {
b, err := io.ReadAll(r.Body)
if err != nil {
errResp = &errorResponse{
Code: http.StatusInternalServerError,
Message: "failed to read request body",
}
}
if err := unmarshalRequest(r.Header.Get(ContentType), b, &requestBody); err != nil {
errResp = &errorResponse{
Code: http.StatusInternalServerError,
Message: "failed to unmarshal request with content-type " + r.Header.Get(ContentType),
}
}
}
// request failed to unmarshal, return with failure
if errResp != nil {
w.WriteHeader(errResp.Code)
if opts.verbose {
b, _ := json.Marshal(errResp)
w.Write(b)
}
return
}
req := &Request[I]{r: r, body: &requestBody}
response := &Response[O]{w: w}
// call the handler
fn(req, response)
var bodyBytes []byte
if response.body != nil {
// if there is a custom marshaler, prioritize it
if response.marshal != nil {
b, err := response.marshal(*response.body)
if err != nil {
errResp = &errorResponse{
Code: http.StatusInternalServerError,
Message: "failed to marshal response with custom marhsaler",
}
}
bodyBytes = b
} else {
// client preferred content-type
b, err := marshalResponse(r.Header.Get(Accept), response.body)
if err != nil {
// server preferred content-type
contentType := response.w.Header().Get(ContentType)
if len(contentType) == 0 {
contentType = opts.defaultContentType
}
b, err = marshalResponse(contentType, response.body)
if err != nil {
errResp = &errorResponse{
Code: http.StatusInternalServerError,
Message: "failed to marshal response with content-type: " + contentType,
}
}
}
bodyBytes = b
}
// Response failed to marshal
if errResp != nil {
w.WriteHeader(errResp.Code)
if opts.verbose {
b, _ := json.Marshal(errResp)
w.Write(b)
}
return
}
}
// ensure user supplied status code is valid
if validStatusCode(response.statusCode) {
w.WriteHeader(response.statusCode)
}
if len(bodyBytes) > 0 {
w.Write(bodyBytes)
}
}
}
// Get requests a representation of the specified resource. Expects an empty request body. If a request
// body is set, it will be ignored.
func Get[I EmptyBody, O any](fn HandleFunc[I, O], options ...Options) http.HandlerFunc {
opts := defaultOptions()
for _, opt := range options {
opt.Apply(opts)
}
return func(w http.ResponseWriter, r *http.Request) {
var errResp *errorResponse
if r.Method != http.MethodGet {
errResp = &errorResponse{
Code: http.StatusMethodNotAllowed,
Message: "invalid method used, expected GET found " + r.Method,
}
}
req := &Request[I]{r: r}
response := &Response[O]{w: w}
// call the handler
fn(req, response)
var bodyBytes []byte
if response.body != nil {
// if there is a custom marshaler, prioritize it
if response.marshal != nil {
b, err := response.marshal(*response.body)
if err != nil {
errResp = &errorResponse{
Code: http.StatusInternalServerError,
Message: "failed to marshal response with custom marhsaler",
}
}
bodyBytes = b
} else {
// client preferred content-type
b, err := marshalResponse(r.Header.Get(Accept), response.body)
if err != nil {
// server preferred content-type
contentType := response.w.Header().Get(ContentType)
if len(contentType) == 0 {
contentType = opts.defaultContentType
}
b, err = marshalResponse(contentType, response.body)
if err != nil {
errResp = &errorResponse{
Code: http.StatusInternalServerError,
Message: "failed to marshal response with content-type: " + contentType,
}
}
}
bodyBytes = b
}
// Response failed to marshal
if errResp != nil {
w.WriteHeader(errResp.Code)
if opts.verbose {
b, _ := json.Marshal(errResp)
w.Write(b)
}
return
}
}
// ensure user supplied status code is valid
if validStatusCode(response.statusCode) {
w.WriteHeader(response.statusCode)
}
if len(bodyBytes) > 0 {
w.Write(bodyBytes)
}
}
}
// Patch method is used to apply partial modifications to a resource. Required Request Body
func Patch[I Body, O Body](fn HandleFunc[I, O], options ...Options) http.HandlerFunc {
opts := defaultOptions()
for _, opt := range options {
opt.Apply(opts)
}
return func(w http.ResponseWriter, r *http.Request) {
var errResp *errorResponse
if r.Method != http.MethodPatch {
errResp = &errorResponse{
Code: http.StatusMethodNotAllowed,
Message: "invalid method used, expected PATCH found " + r.Method,
}
}
var requestBody I
// check for request body
if r.Body != nil || r.ContentLength >= 0 {
b, err := io.ReadAll(r.Body)
if err != nil {
errResp = &errorResponse{
Code: http.StatusInternalServerError,
Message: "failed to read request body",
}
}
if err := unmarshalRequest(r.Header.Get(ContentType), b, &requestBody); err != nil {
errResp = &errorResponse{
Code: http.StatusInternalServerError,
Message: "failed to unmarshal request with content-type " + r.Header.Get(ContentType),
}
}
} else {
errResp = &errorResponse{
Code: http.StatusBadRequest,
Message: "missing request body",
}
}
// request failed to unmarshal, return with failure
if errResp != nil {
w.WriteHeader(errResp.Code)
if opts.verbose {
b, _ := json.Marshal(errResp)
w.Write(b)
}
return
}
req := &Request[I]{r: r, body: &requestBody}
response := &Response[O]{w: w, statusCode: http.StatusOK}
// call the handler
fn(req, response)
var bodyBytes []byte
if response.body != nil {
// if there is a custom marshaler, prioritize it
if response.marshal != nil {
b, err := response.marshal(*response.body)
if err != nil {
errResp = &errorResponse{
Code: http.StatusInternalServerError,
Message: "failed to marshal response with custom marhsaler",
}
}
bodyBytes = b
} else {
// client preferred content-type
b, err := marshalResponse(r.Header.Get(Accept), response.body)
if err != nil {
// server preferred content-type
contentType := response.w.Header().Get(ContentType)
if len(contentType) == 0 {
contentType = opts.defaultContentType
}
b, err = marshalResponse(contentType, response.body)
if err != nil {
errResp = &errorResponse{
Code: http.StatusInternalServerError,
Message: "failed to marshal response with content-type: " + contentType,
}
}
}
bodyBytes = b
}
// Response failed to marshal
if errResp != nil {
w.WriteHeader(errResp.Code)
if opts.verbose {
b, _ := json.Marshal(errResp)
w.Write(b)
}
return
}
}
// ensure user supplied status code is valid
if validStatusCode(response.statusCode) {
w.WriteHeader(response.statusCode)
}
if len(bodyBytes) > 0 {
w.Write(bodyBytes)
}
}
}
// Post method can be used in two different ways, create a resource or perform and operation:. Optional request body
func Post[I Body, O Body](fn HandleFunc[I, O], options ...Options) http.HandlerFunc {
opts := defaultOptions()
for _, opt := range options {
opt.Apply(opts)
}
return func(w http.ResponseWriter, r *http.Request) {
var errResp *errorResponse
if r.Method != http.MethodPost {
errResp = &errorResponse{
Code: http.StatusMethodNotAllowed,
Message: "invalid method used, expected POST found " + r.Method,
}
}
var requestBody I
// check for request body
if r.Body != nil || r.ContentLength >= 0 {
b, err := io.ReadAll(r.Body)
if err != nil {
errResp = &errorResponse{
Code: http.StatusInternalServerError,
Message: "failed to read request body",
}
}
if err := unmarshalRequest(r.Header.Get(ContentType), b, &requestBody); err != nil {
errResp = &errorResponse{
Code: http.StatusInternalServerError,
Message: "failed to unmarshal request with content-type " + r.Header.Get(ContentType),
}
}
}
// request failed to unmarshal, return with failure
if errResp != nil {
w.WriteHeader(errResp.Code)
if opts.verbose {
b, _ := json.Marshal(errResp)
w.Write(b)
}
return
}
req := &Request[I]{r: r, body: &requestBody}
response := &Response[O]{w: w, statusCode: http.StatusOK}
// call the handler
fn(req, response)
var bodyBytes []byte
if response.body != nil {
// if there is a custom marshaler, prioritize it
if response.marshal != nil {
b, err := response.marshal(*response.body)
if err != nil {
errResp = &errorResponse{
Code: http.StatusInternalServerError,
Message: "failed to marshal response with custom marhsaler",
}
}
bodyBytes = b
} else {
// client preferred content-type
b, err := marshalResponse(r.Header.Get(Accept), response.body)
if err != nil {
// server preferred content-type
contentType := response.w.Header().Get(ContentType)
if len(contentType) == 0 {
contentType = opts.defaultContentType
}
b, err = marshalResponse(contentType, response.body)
if err != nil {
errResp = &errorResponse{
Code: http.StatusInternalServerError,
Message: "failed to marshal response with content-type: " + contentType,
}
}
}
bodyBytes = b
}
// Response failed to marshal
if errResp != nil {
w.WriteHeader(errResp.Code)
if opts.verbose {
b, _ := json.Marshal(errResp)
w.Write(b)
}
return
}
}
// ensure user supplied status code is valid
if validStatusCode(response.statusCode) {
w.WriteHeader(response.statusCode)
}
if len(bodyBytes) > 0 {
w.Write(bodyBytes)
}
}
}
// Put method is used to replace a resource with a similar resource that includes a different set of values. Requires request body
func Put[I Body, O Body](fn HandleFunc[I, O], options ...Options) http.HandlerFunc {
opts := defaultOptions()
for _, opt := range options {
opt.Apply(opts)
}
return func(w http.ResponseWriter, r *http.Request) {
var errResp *errorResponse
if r.Method != http.MethodPut {
errResp = &errorResponse{
Code: http.StatusMethodNotAllowed,
Message: "invalid method used, expected PUT found " + r.Method,
}
}
var requestBody I
// check for request body
if r.Body != nil || r.ContentLength >= 0 {
b, err := io.ReadAll(r.Body)
if err != nil {
errResp = &errorResponse{
Code: http.StatusInternalServerError,
Message: "failed to read request body",
}
}
if err := unmarshalRequest(r.Header.Get(ContentType), b, &requestBody); err != nil {
errResp = &errorResponse{
Code: http.StatusInternalServerError,
Message: "failed to unmarshal request with content-type " + r.Header.Get(ContentType),
}
}
} else {
errResp = &errorResponse{
Code: http.StatusBadRequest,
Message: "missing request body",
}
}
// request failed to unmarshal, return with failure
if errResp != nil {
w.WriteHeader(errResp.Code)
if opts.verbose {
b, _ := json.Marshal(errResp)
w.Write(b)
}
return
}
req := &Request[I]{r: r, body: &requestBody}
response := &Response[O]{w: w, statusCode: http.StatusOK}
// call the handler
fn(req, response)
var bodyBytes []byte
if response.body != nil {
// if there is a custom marshaler, prioritize it
if response.marshal != nil {
b, err := response.marshal(*response.body)
if err != nil {
errResp = &errorResponse{
Code: http.StatusInternalServerError,
Message: "failed to marshal response with custom marhsaler",
}
}
bodyBytes = b
} else {
// client preferred content-type
b, err := marshalResponse(r.Header.Get(Accept), response.body)
if err != nil {
// server preferred content-type
contentType := response.w.Header().Get(ContentType)
if len(contentType) == 0 {
contentType = opts.defaultContentType
}
b, err = marshalResponse(contentType, response.body)
if err != nil {
errResp = &errorResponse{
Code: http.StatusInternalServerError,
Message: "failed to marshal response with content-type: " + contentType,
}
}
}
bodyBytes = b
}
// Response failed to marshal
if errResp != nil {
w.WriteHeader(errResp.Code)
if opts.verbose {
b, _ := json.Marshal(errResp)
w.Write(b)
}
return
}
}
// ensure user supplied status code is valid
if validStatusCode(response.statusCode) {
w.WriteHeader(response.statusCode)
}
if len(bodyBytes) > 0 {
w.Write(bodyBytes)
}
}
}
func unmarshalRequest(contentType string, b []byte, body Body) error {
switch contentType {
case ContentProto:
// msg pointer matches body
msg, ok := body.(proto.Message)
if !ok {
return ErrProto
}
if err := proto.Unmarshal(b, msg); err != nil {
return err
}
return nil
case ContentJSON:
// default application/json
if err := json.Unmarshal(b, body); err != nil {
return err
}
return nil
default:
return ErrUnsupportedRequestType
}
}
func marshalResponse(contentType string, body Body) ([]byte, error) {
switch contentType {
case ContentProto:
msg, ok := body.(proto.Message)
if !ok {
return nil, ErrProto
}
b, err := proto.Marshal(msg)
if err != nil {
return nil, err
}
return b, nil
case ContentJSON:
b, err := json.Marshal(body)
if err != nil {
return nil, err
}
return b, nil
default:
return nil, ErrUnsupportedRequestType
}
}
func validStatusCode(statusCode int) bool {
return (statusCode >= 100 && statusCode <= 999)
}