PopulateRequestContext returns a middleware which populates a number of standard HTTP header values into the request context. Those values may be extracted using the corresponding ContextKey type in this package.
()
| 9 | // values into the request context. Those values may be extracted using the |
| 10 | // corresponding ContextKey type in this package. |
| 11 | func PopulateRequestContext() func(http.Handler) http.Handler { |
| 12 | return func(h http.Handler) http.Handler { |
| 13 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 14 | ctx := r.Context() |
| 15 | for k, v := range map[ctxKey]string{ |
| 16 | RequestMethodKey: r.Method, |
| 17 | RequestURIKey: r.RequestURI, |
| 18 | RequestPathKey: r.URL.Path, |
| 19 | RequestProtoKey: r.Proto, |
| 20 | RequestHostKey: r.Host, |
| 21 | RequestRemoteAddrKey: r.RemoteAddr, |
| 22 | RequestXForwardedForKey: r.Header.Get("X-Forwarded-For"), |
| 23 | RequestXRealIPKey: r.Header.Get("X-Real-Ip"), |
| 24 | RequestXForwardedProtoKey: r.Header.Get("X-Forwarded-Proto"), |
| 25 | RequestAuthorizationKey: r.Header.Get("Authorization"), |
| 26 | RequestRefererKey: r.Header.Get("Referer"), |
| 27 | RequestUserAgentKey: r.Header.Get("User-Agent"), |
| 28 | RequestXRequestIDKey: r.Header.Get("X-Request-Id"), |
| 29 | RequestXCSRFTokenKey: r.Header.Get("X-Csrf-Token"), |
| 30 | RequestAcceptKey: r.Header.Get("Accept"), |
| 31 | } { |
| 32 | ctx = context.WithValue(ctx, k, v) |
| 33 | } |
| 34 | h.ServeHTTP(w, r.WithContext(ctx)) |
| 35 | }) |
| 36 | } |
| 37 | } |