/
request.go
68 lines (58 loc) · 1.41 KB
/
request.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
package interceptor
import (
"context"
"net/url"
"connectrpc.com/connect"
"google.golang.org/grpc/metadata"
)
// WithContext set up the context
func WithContext() connect.Option {
interFn := func(next connect.UnaryFunc) connect.UnaryFunc {
// prepare the callback
fn := func(ctx context.Context, r connect.AnyRequest) (connect.AnyResponse, error) {
if r.Spec().IsClient {
kv, ok := metadata.FromOutgoingContext(ctx)
if !ok {
kv = metadata.MD{}
}
// copy the headers to the context
for k, vv := range kv {
for _, v := range vv {
r.Header().Add(k, v)
}
}
} else {
kv, ok := metadata.FromIncomingContext(ctx)
if !ok {
kv = metadata.MD{}
}
// copy the headers to the context
for k, v := range r.Header() {
kv.Set(k, v...)
}
// prepare the context
ctx = metadata.NewIncomingContext(ctx, kv)
}
// execute the method
return next(ctx, r)
}
return fn
}
unaryFn := connect.UnaryInterceptorFunc(interFn)
// prepare the option
return connect.WithInterceptors(unaryFn)
}
// GetRequestURL returns the request URL
func GetRequestURL(r connect.AnyRequest) *url.URL {
uri := &url.URL{
Scheme: "http",
Host: r.Header().Get("Host"),
}
if value := r.Header().Get("X-Forwarded-Host"); value != "" {
uri.Host = value
}
if value := r.Header().Get("X-Forwarded-Proto"); value != "" {
uri.Scheme = value
}
return uri
}