Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix for parsing port at log middleware #4348

Merged
merged 3 commits into from
Jun 23, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 17 additions & 6 deletions pkg/logging/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"net"
"sort"
"strings"

"net/http"
"time"
Expand Down Expand Up @@ -43,14 +44,24 @@ func (m *HTTPServerMiddleware) HTTPMiddleware(name string, next http.Handler) ht
if hostPort == "" {
hostPort = r.URL.Host
}
_, port, err := net.SplitHostPort(hostPort)
if err != nil {
level.Error(m.logger).Log("msg", "failed to parse host port for http log decision", "err", err)
next.ServeHTTP(w, r)
return

var port string
var err error
// Try to extract port if there is ':' as part of 'hostPort'.
if strings.Contains(hostPort, ":") {
_, port, err = net.SplitHostPort(hostPort)
if err != nil {
level.Error(m.logger).Log("msg", "failed to parse host port for http log decision", "err", err)
next.ServeHTTP(w, r)
return
}
}

decision := m.opts.shouldLog(net.JoinHostPort(r.URL.String(), port), nil)
deciderURL := r.URL.String()
if len(port) > 0 {
deciderURL = net.JoinHostPort(deciderURL, port)
}
decision := m.opts.shouldLog(deciderURL, nil)

switch decision {
case NoLogCall:
Expand Down
15 changes: 15 additions & 0 deletions pkg/logging/http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,19 @@ func TestHTTPServerMiddleware(t *testing.T) {
testutil.Equals(t, 200, resp.StatusCode)
testutil.Equals(t, "Test Works", string(body))
testutil.Assert(t, !strings.Contains(b.String(), "err="))

// URL with no explicit port number in the format- hostname:port
req = httptest.NewRequest("GET", "http://example.com/foo", nil)
b.Reset()

w = httptest.NewRecorder()
hm(w, req)

resp = w.Result()
body, err = ioutil.ReadAll(resp.Body)
testutil.Ok(t, err)

testutil.Equals(t, 200, resp.StatusCode)
testutil.Equals(t, "Test Works", string(body))
testutil.Assert(t, !strings.Contains(b.String(), "err="))
}