RemoteIPHandler is similar to RemoteAddrHandler, but logs only an IP, not a port.
(fieldKey string)
| 106 | // RemoteIPHandler is similar to RemoteAddrHandler, but logs only |
| 107 | // an IP, not a port. |
| 108 | func RemoteIPHandler(fieldKey string) func(next http.Handler) http.Handler { |
| 109 | return func(next http.Handler) http.Handler { |
| 110 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 111 | ip := getHost(r.RemoteAddr) |
| 112 | if ip != "" { |
| 113 | log := zerolog.Ctx(r.Context()) |
| 114 | log.UpdateContext(func(c zerolog.Context) zerolog.Context { |
| 115 | return c.Str(fieldKey, ip) |
| 116 | }) |
| 117 | } |
| 118 | next.ServeHTTP(w, r) |
| 119 | }) |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | // UserAgentHandler adds the request's user-agent as a field to the context's logger |
| 124 | // using fieldKey as field key. |