This repository has been archived by the owner on Jan 17, 2022. It is now read-only.
/
request_func.go
78 lines (66 loc) · 2.29 KB
/
request_func.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
package option
import (
"context"
"net"
"net/http"
"strings"
"github.com/DoNewsCode/core-kit/mw"
grpctransport "github.com/go-kit/kit/transport/grpc"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/peer"
"github.com/DoNewsCode/core/contract"
httptransport "github.com/go-kit/kit/transport/http"
)
// IPToHTTPContext is a httptransport.RequestFun that put client ip to context,
// under contract.IpKey.
func IPToHTTPContext() httptransport.RequestFunc {
return func(ctx context.Context, r *http.Request) context.Context {
return context.WithValue(ctx, contract.IpKey, realIP(r))
}
}
// IPToGRPCContext is a grpctransport.ServerRequestFunc that put client ip to
// context, under contract.IpKey.
func IPToGRPCContext() grpctransport.ServerRequestFunc {
return func(ctx context.Context, md metadata.MD) context.Context {
remote, _ := peer.FromContext(ctx)
ip, _, _ := net.SplitHostPort(remote.Addr.String())
return context.WithValue(ctx, contract.IpKey, ip)
}
}
// TransportToHTTPContext adds transport information to the context.
func TransportToHTTPContext() httptransport.RequestFunc {
return func(ctx context.Context, request *http.Request) context.Context {
context.WithValue(ctx, contract.RequestUrlKey, request.RequestURI)
return context.WithValue(ctx, contract.TransportKey, mw.HTTPKind)
}
}
// RequestURLToHTTPContext adds path information to the context.
func RequestURLToHTTPContext() httptransport.RequestFunc {
return func(ctx context.Context, request *http.Request) context.Context {
return context.WithValue(ctx, contract.RequestUrlKey, request.RequestURI)
}
}
// TransportToGRPCContext adds path and transport information to the context.
func TransportToGRPCContext() grpctransport.ServerRequestFunc {
return func(ctx context.Context, md metadata.MD) context.Context {
return context.WithValue(ctx, contract.TransportKey, mw.GRPCKind)
}
}
func realIP(r *http.Request) string {
var ip string
var xForwardedFor = http.CanonicalHeaderKey("X-Forwarded-For")
var xRealIP = http.CanonicalHeaderKey("X-Real-IP")
if xff := r.Header.Get(xForwardedFor); xff != "" {
i := strings.Index(xff, ", ")
if i == -1 {
i = len(xff)
}
ip = xff[:i]
return ip
}
if xrip := r.Header.Get(xRealIP); xrip != "" {
return xrip
}
ip, _, _ = net.SplitHostPort(r.RemoteAddr)
return ip
}