Skip to content

Commit

Permalink
Make RemoteAddrHandler copy the RemoteAddr untouched (#347)
Browse files Browse the repository at this point in the history
Do not remove the port part of the RemoteAddr and accept values with no ports.
  • Loading branch information
Vivalldi committed Aug 19, 2021
1 parent be6f6fd commit fe93100
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 5 deletions.
5 changes: 2 additions & 3 deletions hlog/hlog.go
Expand Up @@ -3,7 +3,6 @@ package hlog

import (
"context"
"net"
"net/http"
"time"

Expand Down Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions hlog/hlog_test.go
Expand Up @@ -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)
}
}
Expand All @@ -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)
}
}
Expand Down

0 comments on commit fe93100

Please sign in to comment.