-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathctx.go
55 lines (45 loc) · 1.34 KB
/
ctx.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
package main
import (
"context"
"log"
"net"
"net/http"
"strings"
)
type ipCtxKey int
const ctxKey ipCtxKey = iota
// Creates a new context containing the request's originating IP.
// Preference: X-Forwarded-For, X-Real-IP, RemoteAddress
func newCtxUserIP(ctx context.Context, r *http.Request) context.Context {
split := strings.Split(r.RemoteAddr, ":")
uip := split[0]
xFwdFor := http.CanonicalHeaderKey("X-Forwarded-For")
if _, ok := r.Header[xFwdFor]; ok {
fwdaddr := r.Header[xFwdFor]
split := strings.Split(fwdaddr[len(fwdaddr)-1], ":")
uip = split[0]
return context.WithValue(ctx, ctxKey, uip)
}
xRealIP := http.CanonicalHeaderKey("X-Real-IP")
if _, ok := r.Header[xRealIP]; ok {
realip := r.Header[xRealIP]
split := strings.Split(realip[len(realip)-1], ":")
uip = split[0]
}
return context.WithValue(ctx, ctxKey, uip)
}
// Yoinks the IP address from the request's context
func getIPFromCtx(ctx context.Context) net.IP {
uip, ok := ctx.Value(ctxKey).(string)
if !ok {
log.Printf("Couldn't retrieve IP From Request\n")
}
return net.ParseIP(uip)
}
// Middleware to yeet the remote IP address into the request struct
func ipMiddleware(hop http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := newCtxUserIP(r.Context(), r)
hop.ServeHTTP(w, r.WithContext(ctx))
})
}