-
Notifications
You must be signed in to change notification settings - Fork 322
/
middleware.go
41 lines (37 loc) · 1.18 KB
/
middleware.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
package graph
import (
"context"
"net/http"
"strings"
"github.com/highlight-run/highlight/backend/model"
)
func PublicMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// get users ip for geolocation data
IPAddress := r.Header.Get("X-Real-Ip")
if IPAddress == "" {
IPAddress = r.Header.Get("X-Client-IP")
}
if IPAddress == "" {
IPAddress = r.Header.Get("X-Forwarded-For")
if IPAddress != "" && strings.Contains(IPAddress, ",") {
if ipList := strings.Split(IPAddress, ","); len(ipList) > 0 {
IPAddress = ipList[0]
}
}
}
if IPAddress == "" {
IPAddress = r.RemoteAddr
}
// get user-agent string
UserAgent := r.Header.Get("user-agent")
// get the accept-language string
AcceptLanguage := r.Header.Get("Accept-Language")
// Pass the user's id, ip address, user agent, and accept-language through context.
ctx := context.WithValue(r.Context(), model.ContextKeys.IP, IPAddress)
ctx = context.WithValue(ctx, model.ContextKeys.UserAgent, UserAgent)
ctx = context.WithValue(ctx, model.ContextKeys.AcceptLanguage, AcceptLanguage)
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
})
}