/
gw_server_options.go
284 lines (238 loc) · 7.7 KB
/
gw_server_options.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
// Copyright (c) 2021 rookie-ninja
//
// Use of this source code is governed by an Apache-style
// license that can be found in the LICENSE file.
package rkgrpc
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/textproto"
"strings"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
rkmid "github.com/rookie-ninja/rk-entry/v2/middleware"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/encoding/protojson"
)
// Gateway options for marshaller and unmarshaler.
//
// The inner fields was defined as pointer instead of reference which look strange.
//
// It is because we hope to make sure the value was defined by user in YAML file.
// Otherwise, the boolean value will always be false even there nothing in YAML file.
type gwOption struct {
Marshal *struct {
Multiline *bool `yaml:"multiline" json:"multiline"`
EmitUnpopulated *bool `yaml:"emitUnpopulated" json:"emitUnpopulated"`
Indent *string `yaml:"indent" json:"indent"`
AllowPartial *bool `yaml:"allowPartial" json:"allowPartial"`
UseProtoNames *bool `yaml:"useProtoNames" json:"useProtoNames"`
UseEnumNumbers *bool `yaml:"useEnumNumbers" json:"useEnumNumbers"`
} `yaml:"marshal" json:"marshal"`
Unmarshal *struct {
AllowPartial *bool `yaml:"allowPartial" json:"allowPartial"`
DiscardUnknown *bool `yaml:"discardUnknown" json:"discardUnknown"`
} `yaml:"unmarshal" json:"unmarshal"`
}
// Convert gwOption to protojson.MarshalOptions
func toMarshalOptions(opt *gwOption) *protojson.MarshalOptions {
res := &protojson.MarshalOptions{}
if opt == nil || opt.Marshal == nil {
return res
}
// Parse fields on by one
if opt.Marshal.Multiline != nil {
res.Multiline = *opt.Marshal.Multiline
}
if opt.Marshal.EmitUnpopulated != nil {
res.EmitUnpopulated = *opt.Marshal.EmitUnpopulated
}
if opt.Marshal.Indent != nil {
res.Indent = *opt.Marshal.Indent
}
if opt.Marshal.AllowPartial != nil {
res.AllowPartial = *opt.Marshal.AllowPartial
}
if opt.Marshal.UseProtoNames != nil {
res.UseProtoNames = *opt.Marshal.UseProtoNames
}
if opt.Marshal.UseEnumNumbers != nil {
res.UseEnumNumbers = *opt.Marshal.UseEnumNumbers
}
return res
}
// Convert gwOption to protojson.UnmarshalOptions
func toUnmarshalOptions(opt *gwOption) *protojson.UnmarshalOptions {
res := &protojson.UnmarshalOptions{}
if opt == nil || opt.Unmarshal == nil {
return res
}
if opt.Unmarshal.AllowPartial != nil {
res.AllowPartial = *opt.Unmarshal.AllowPartial
}
if opt.Unmarshal.DiscardUnknown != nil {
res.DiscardUnknown = *opt.Unmarshal.DiscardUnknown
}
return res
}
// Merge gwOption with default RK style protojson.MarshalOptions
func mergeWithRkGwMarshalOption(opt *gwOption) *protojson.MarshalOptions {
res := &protojson.MarshalOptions{
UseProtoNames: false,
EmitUnpopulated: true,
}
if opt == nil || opt.Marshal == nil {
return res
}
// Parse fields on by one
if opt.Marshal.Multiline != nil {
res.Multiline = *opt.Marshal.Multiline
}
if opt.Marshal.EmitUnpopulated != nil {
res.EmitUnpopulated = *opt.Marshal.EmitUnpopulated
}
if opt.Marshal.Indent != nil {
res.Indent = *opt.Marshal.Indent
}
if opt.Marshal.AllowPartial != nil {
res.AllowPartial = *opt.Marshal.AllowPartial
}
if opt.Marshal.UseProtoNames != nil {
res.UseProtoNames = *opt.Marshal.UseProtoNames
}
if opt.Marshal.UseEnumNumbers != nil {
res.UseEnumNumbers = *opt.Marshal.UseEnumNumbers
}
return res
}
// Merge gwOption with default RK style protojson.UnmarshalOptions
func mergeWithRkGwUnmarshalOption(opt *gwOption) *protojson.UnmarshalOptions {
res := &protojson.UnmarshalOptions{}
if opt == nil || opt.Unmarshal == nil {
return res
}
// Parse fields on by one
if opt.Unmarshal.AllowPartial != nil {
res.AllowPartial = *opt.Unmarshal.AllowPartial
}
if opt.Unmarshal.DiscardUnknown != nil {
res.DiscardUnknown = *opt.Unmarshal.DiscardUnknown
}
return res
}
// NewRkGwServerMuxOptions creates new gw server mux options.
func NewRkGwServerMuxOptions(mOptIn *protojson.MarshalOptions, uOptIn *protojson.UnmarshalOptions) []runtime.ServeMuxOption {
mOpt := &protojson.MarshalOptions{
UseProtoNames: false,
EmitUnpopulated: true,
}
if mOptIn != nil {
mOpt = mOptIn
}
uOpt := &protojson.UnmarshalOptions{}
if uOptIn != nil {
uOpt = uOptIn
}
return []runtime.ServeMuxOption{
runtime.WithErrorHandler(HttpErrorHandler),
runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{
MarshalOptions: *mOpt,
UnmarshalOptions: *uOpt,
}),
runtime.WithMetadata(rkGwMetadataBuilder),
runtime.WithOutgoingHeaderMatcher(OutgoingHeaderMatcher),
runtime.WithIncomingHeaderMatcher(IncomingHeaderMatcher),
}
}
func rkGwMetadataBuilder(c context.Context, req *http.Request) metadata.MD {
// we are unable to get scheme with req.URL.Scheme.
// Let's check with TLS.
scheme := "http"
if req.TLS != nil {
scheme = "https"
}
md := metadata.Pairs(
"x-forwarded-method", req.Method,
"x-forwarded-path", req.URL.Path,
"x-forwarded-scheme", scheme,
"x-forwarded-remote-addr", req.RemoteAddr,
"x-forwarded-user-agent", req.UserAgent())
if pattern, ok := runtime.HTTPPathPattern(c); ok {
md["x-forwarded-pattern"] = []string{pattern}
}
return md
}
// HttpErrorHandler Mainly copies from runtime.DefaultHTTPErrorHandler.
// We reformat error response with rkerror.ErrorResp.
func HttpErrorHandler(ctx context.Context, mux *runtime.ServeMux, marshaler runtime.Marshaler, w http.ResponseWriter, r *http.Request, err error) {
s := status.Convert(err)
pb := s.Proto()
w.Header().Del("Trailer")
w.Header().Del("Transfer-Encoding")
contentType := marshaler.ContentType(pb)
w.Header().Set("Content-Type", contentType)
resp := rkmid.GetErrorBuilder().New(runtime.HTTPStatusFromCode(s.Code()), s.Message(), s.Details()...)
md, _ := runtime.ServerMetadataFromContext(ctx)
// handle forward response server metadata
for k, vs := range md.HeaderMD {
if h, ok := OutgoingHeaderMatcher(k); ok {
for _, v := range vs {
w.Header().Add(h, v)
}
}
}
// RFC 7230 https://tools.ietf.org/html/rfc7230#section-4.1.2
// Unless the request includes a TE header field indicating "trailers"
// is acceptable, as described in Section 4.3, a server SHOULD NOT
// generate trailer fields that it believes are necessary for the user
// agent to receive.
var wantsTrailers bool
if te := r.Header.Get("TE"); strings.Contains(strings.ToLower(te), "trailers") {
wantsTrailers = true
// handle forward response trailer header
for k := range md.TrailerMD {
tKey := textproto.CanonicalMIMEHeaderKey(fmt.Sprintf("%s%s", runtime.MetadataTrailerPrefix, k))
w.Header().Add("Trailer", tKey)
}
w.Header().Set("Transfer-Encoding", "chunked")
}
st := runtime.HTTPStatusFromCode(s.Code())
w.WriteHeader(st)
bytes, _ := json.Marshal(resp)
if _, err := w.Write(bytes); err != nil {
grpclog.Infof("Failed to write response: %v", err)
}
if wantsTrailers {
// handle forward response trailer
for k, vs := range md.TrailerMD {
tKey := fmt.Sprintf("%s%s", runtime.MetadataTrailerPrefix, k)
for _, v := range vs {
w.Header().Add(tKey, v)
}
}
}
}
// OutgoingHeaderMatcher Pass out all metadata in grpc to http header.
func OutgoingHeaderMatcher(key string) (string, bool) {
return key, true
}
// IncomingHeaderMatcher Pass out all metadata in http header to grpc metadata.
func IncomingHeaderMatcher(key string) (string, bool) {
key = textproto.CanonicalMIMEHeaderKey(key)
if isForbiddenHeader(key) {
return "", false
}
return key, true
}
// isForbiddenHeader checks whether hdr belongs to the list of
// forbidden headers by gRPC
func isForbiddenHeader(hdr string) bool {
switch hdr {
case "Connection":
return true
}
return false
}