-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstandard.go
84 lines (77 loc) · 2.26 KB
/
standard.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
package httpwrap
import (
"encoding/json"
"log"
"net/http"
)
// The StandardRequestReader decodes the request using the following:
//
// - Cookies
//
// - Query Params
//
// - Request Headers
//
// - Request Path Segment (e.g: /api/pets/{id})
//
// - JSON Decoding of the http request body
func StandardRequestReader() RequestReader {
decoder := NewDecoder()
return func(_ http.ResponseWriter, req *http.Request, obj any) error {
return decoder.Decode(req, obj)
}
}
// StandardResponseWriter will try to cast the error and response objects to the
// HTTPResponse interface and use them to send the response to the client.
// By default, it will send a 200 OK and encode the response object as JSON.
// If the HTTPResponse has a `0` StatusCode, WriteHeader will not be called.
// If the error is not an HTTPResponse, a 500 status code will be returned with
// the body being exactly the error's string.
func StandardResponseWriter() ResponseWriter {
return func(w http.ResponseWriter, _ *http.Request, res any, err error) {
if err != nil {
if cast, ok := err.(HTTPResponse); ok {
code := cast.StatusCode()
if code != 0 {
w.WriteHeader(cast.StatusCode())
}
if sendError := cast.WriteBody(w); sendError != nil {
log.Println("error writing response:", sendError)
}
} else {
w.WriteHeader(http.StatusInternalServerError)
if _, sendError := w.Write([]byte(err.Error())); sendError != nil {
log.Println("error writing response:", sendError)
}
}
return
}
if res == nil {
return
}
if cast, ok := res.(HTTPResponse); ok {
code := cast.StatusCode()
if code != 0 {
w.WriteHeader(cast.StatusCode())
}
if sendError := cast.WriteBody(w); sendError != nil {
log.Println("error writing response:", sendError)
}
return
}
w.WriteHeader(http.StatusOK)
encoder := json.NewEncoder(w)
if sendError := encoder.Encode(res); sendError != nil {
log.Println("Error writing response:", sendError)
}
}
}
// NewStandardWrapper returns a new wrapper using the StandardRequestReader and the
// StandardResponseWriter.
func NewStandardWrapper() Wrapper {
constructor := StandardRequestReader()
responseWriter := StandardResponseWriter()
return New().
WithRequestReader(constructor).
Finally(responseWriter)
}