-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.go
216 lines (180 loc) · 5.03 KB
/
response.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
package response
import (
"context"
"encoding/json"
"net/http"
"strings"
"github.com/labstack/echo/v4"
"github.com/valyala/fasthttp"
"google.golang.org/grpc/status"
)
const (
customHeaderPrefix = "handler-attribute-"
customResponseCode = "handler-response-code"
)
var contentTypeHeader = http.CanonicalHeaderKey("Content-Type")
// ResponserFasthttp is a behavior that a struct may have to format its fields
// in case of an HTTP response.
type ResponserFasthttp interface {
HttpResponse() interface{}
}
type ResponserEcho interface {
HttpResponseBytes() ([]byte, error)
}
type Response struct {
customCode int
serviceName string
contentType string
ctx interface{}
}
type Options struct {
ServiceName string
}
// NewFromFasthttp creates a new response container for HTTP handlers return data using a
// specific standard.
func NewFromFasthttp(ctx *fasthttp.RequestCtx, options *Options) *Response {
return &Response{
serviceName: options.ServiceName,
contentType: string(ctx.Request.Header.Peek(contentTypeHeader)),
ctx: ctx,
}
}
func NewFromEcho(ctx echo.Context, options *Options) *Response {
return &Response{
serviceName: options.ServiceName,
contentType: "application/json",
ctx: ctx,
}
}
func (r *Response) ForwardAuthenticationError(err error) error {
ferror, err := serviceErrorFromString(err.Error())
if err != nil {
return r.forwardOutput(fasthttp.StatusInternalServerError,
newResponseError(&responseErrorOptions{
Message: internalServerErrorMsg,
Details: err.Error(),
}),
)
}
if ferror.IsKnownError() {
return r.forwardOutput(ferror.ResponseCode(), ferror.ToResponseError())
}
return nil
}
func (r *Response) ForwardError(err error) error {
ferror, err := serviceErrorFromString(err.Error())
if err != nil {
return r.forwardOutput(fasthttp.StatusInternalServerError,
newResponseError(&responseErrorOptions{
Message: internalServerErrorMsg,
Details: err.Error(),
}),
)
}
if ferror.IsKnownError() {
return r.forwardOutput(ferror.ResponseCode(), ferror.ToResponseError())
}
// A gRPC service can send "gRPC" errors in case of unexpected errors
if sts, ok := status.FromError(err); ok {
return r.forwardOutput(fasthttp.StatusInternalServerError,
newResponseError(&responseErrorOptions{
Message: internalServerErrorMsg,
Details: sts.Message(),
}),
)
}
// In case some parsing failed.
if res, ok := jsonError(err); ok {
return r.forwardOutput(fasthttp.StatusBadRequest, res)
}
// Forward the original error if none of the above error checks were
// successful.
return r.forwardOutput(fasthttp.StatusInternalServerError,
newResponseError(&responseErrorOptions{
Source: r.serviceName,
Message: internalServerErrorMsg,
Details: err.Error(),
}),
)
}
func (r *Response) ForwardSuccess(data interface{}) error {
if _, ok := r.ctx.(*fasthttp.RequestCtx); ok {
// Does the message have another format to send as response?
if h, ok := data.(ResponserFasthttp); ok {
data = h.HttpResponse()
}
return r.forwardOutput(fasthttp.StatusOK, data)
}
if _, ok := r.ctx.(echo.Context); ok {
if h, ok := data.(ResponserEcho); ok {
b, err := h.HttpResponseBytes()
if err != nil {
return err
}
return r.forwardOutput(fasthttp.StatusOK, string(b))
}
}
return nil
}
func (r *Response) forwardOutput(statusCode int, data interface{}) error {
if fctx, ok := r.ctx.(*fasthttp.RequestCtx); ok {
out, err := json.Marshal(data)
if err != nil {
return r.ForwardError(err)
}
r.setFasthttpCustomHeaders(fctx)
if v := fctx.UserValue(customResponseCode); v != nil {
if c, ok := v.(int); ok {
statusCode = c
}
}
fctx.Response.SetStatusCode(statusCode)
fctx.Response.Header.SetContentType(r.contentType)
fctx.Response.SetBodyRaw(out)
return nil
}
if ectx, ok := r.ctx.(echo.Context); ok {
if r.customCode != 0 {
statusCode = r.customCode
}
ectx.Response().Header().Set("Content-Type", r.contentType)
out, ok := data.(string)
if !ok {
b, err := json.Marshal(data)
if err != nil {
return r.ForwardError(err)
}
out = string(b)
}
if err := ectx.String(statusCode, out); err != nil {
return err
}
}
return nil
}
func (r *Response) setFasthttpCustomHeaders(ctx *fasthttp.RequestCtx) {
// Set all handler's custom header values.
ctx.VisitUserValues(func(key []byte, value interface{}) {
if strings.HasPrefix(string(key), customHeaderPrefix) {
ctx.Response.Header.Set(strings.TrimPrefix(string(key), customHeaderPrefix), value.(string))
}
})
}
func (r *Response) SetContentType(contentType string) {
r.contentType = contentType
}
func SetResponseCode(ctx context.Context, code int) {
if c, ok := ctx.(*fasthttp.RequestCtx); ok {
c.SetUserValue(customResponseCode, code)
return
}
r := RetrieveFromContext(ctx)
r.customCode = code
}
func AppendResponseToContext(ctx context.Context, r *Response) context.Context {
return context.WithValue(ctx, "response", r)
}
func RetrieveFromContext(ctx context.Context) *Response {
r := ctx.Value("response")
return r.(*Response)
}