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:
Tyler Cosgrove 2021-08-19 14:46:16 -04:00 committed by GitHub
parent be6f6fd8f1
commit fe931004ff
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 4 additions and 5 deletions

View File

@ -3,7 +3,6 @@ package hlog
import (
"context"
"net"
"net/http"
"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 {
return func(next http.Handler) http.Handler {
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.UpdateContext(func(c zerolog.Context) zerolog.Context {
return c.Str(fieldKey, host)
return c.Str(fieldKey, r.RemoteAddr)
})
}
next.ServeHTTP(w, r)

View File

@ -100,7 +100,7 @@ func TestRemoteAddrHandler(t *testing.T) {
}))
h = NewHandler(zerolog.New(out))(h)
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)
}
}
@ -116,7 +116,7 @@ func TestRemoteAddrHandlerIPv6(t *testing.T) {
}))
h = NewHandler(zerolog.New(out))(h)
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)
}
}