Make RemoteAddrHandler copy the RemoteAddr untouched (#347)
Do not remove the port part of the RemoteAddr and accept values with no ports.
This commit is contained in:
parent
be6f6fd8f1
commit
fe931004ff
|
@ -3,7 +3,6 @@ package hlog
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"net"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
@ -79,10 +78,10 @@ func RequestHandler(fieldKey string) func(next http.Handler) http.Handler {
|
||||||
func RemoteAddrHandler(fieldKey string) func(next http.Handler) http.Handler {
|
func RemoteAddrHandler(fieldKey string) func(next http.Handler) http.Handler {
|
||||||
return func(next http.Handler) http.Handler {
|
return func(next http.Handler) http.Handler {
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
if host, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
|
if r.RemoteAddr != "" {
|
||||||
log := zerolog.Ctx(r.Context())
|
log := zerolog.Ctx(r.Context())
|
||||||
log.UpdateContext(func(c zerolog.Context) zerolog.Context {
|
log.UpdateContext(func(c zerolog.Context) zerolog.Context {
|
||||||
return c.Str(fieldKey, host)
|
return c.Str(fieldKey, r.RemoteAddr)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
next.ServeHTTP(w, r)
|
next.ServeHTTP(w, r)
|
||||||
|
|
|
@ -100,7 +100,7 @@ func TestRemoteAddrHandler(t *testing.T) {
|
||||||
}))
|
}))
|
||||||
h = NewHandler(zerolog.New(out))(h)
|
h = NewHandler(zerolog.New(out))(h)
|
||||||
h.ServeHTTP(nil, r)
|
h.ServeHTTP(nil, r)
|
||||||
if want, got := `{"ip":"1.2.3.4"}`+"\n", decodeIfBinary(out); want != got {
|
if want, got := `{"ip":"1.2.3.4:1234"}`+"\n", decodeIfBinary(out); want != got {
|
||||||
t.Errorf("Invalid log output, got: %s, want: %s", got, want)
|
t.Errorf("Invalid log output, got: %s, want: %s", got, want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -116,7 +116,7 @@ func TestRemoteAddrHandlerIPv6(t *testing.T) {
|
||||||
}))
|
}))
|
||||||
h = NewHandler(zerolog.New(out))(h)
|
h = NewHandler(zerolog.New(out))(h)
|
||||||
h.ServeHTTP(nil, r)
|
h.ServeHTTP(nil, r)
|
||||||
if want, got := `{"ip":"2001:db8:a0b:12f0::1"}`+"\n", decodeIfBinary(out); want != got {
|
if want, got := `{"ip":"[2001:db8:a0b:12f0::1]:1234"}`+"\n", decodeIfBinary(out); want != got {
|
||||||
t.Errorf("Invalid log output, got: %s, want: %s", got, want)
|
t.Errorf("Invalid log output, got: %s, want: %s", got, want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue