-
Notifications
You must be signed in to change notification settings - Fork 0
/
gateway.go
77 lines (69 loc) · 1.89 KB
/
gateway.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
package gateway
import (
"context"
httpi "github.com/hopeio/cherry/utils/net/http"
"net/http"
"net/url"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/hopeio/cherry/utils/encoding/protobuf/jsonpb"
"google.golang.org/grpc/metadata"
)
type GatewayHandler func(context.Context, *runtime.ServeMux)
func Gateway(gatewayHandle GatewayHandler) *runtime.ServeMux {
ctx := context.Background()
gwmux := runtime.NewServeMux(
runtime.WithMarshalerOption(runtime.MIMEWildcard, &jsonpb.JSONPb{}),
runtime.WithMetadata(func(ctx context.Context, req *http.Request) metadata.MD {
area, err := url.PathUnescape(req.Header.Get(httpi.HeaderArea))
if err != nil {
area = ""
}
var token = httpi.GetToken(req)
return map[string][]string{
httpi.HeaderArea: {area},
httpi.HeaderDeviceInfo: {req.Header.Get(httpi.HeaderDeviceInfo)},
httpi.HeaderLocation: {req.Header.Get(httpi.HeaderLocation)},
httpi.HeaderAuthorization: {token},
}
}),
runtime.WithIncomingHeaderMatcher(func(key string) (string, bool) {
switch key {
case
"Accept",
"Accept-Charset",
"Accept-Language",
"Accept-Ranges",
//"Token",
"Cache-Control",
"Content-Type",
//"Cookie",
"Date",
"Expect",
"From",
"Host",
"If-Match",
"If-Modified-Since",
"If-None-Match",
"If-Schedule-Tag-Match",
"If-Unmodified-Since",
"Max-Forwards",
"Origin",
"Pragma",
"Referer",
"User-Agent",
"Via",
"Warning":
return key, true
}
return "", false
}),
runtime.WithOutgoingHeaderMatcher(outgoingHeaderMatcher))
runtime.WithForwardResponseOption(CookieHook)(gwmux)
runtime.WithForwardResponseOption(ResponseHook)(gwmux)
runtime.WithRoutingErrorHandler(RoutingErrorHandler)(gwmux)
runtime.WithErrorHandler(CustomHTTPError)(gwmux)
if gatewayHandle != nil {
gatewayHandle(ctx, gwmux)
}
return gwmux
}