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

pkg/logging: Fix HTTP logging middleware panic #3922

Merged
merged 1 commit into from
Mar 12, 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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ We use _breaking :warning:_ to mark changes that are not backward compatible (re

### Fixed
- [#3204](https://github.com/thanos-io/thanos/pull/3204) Mixin: Use sidecar's metric timestamp for healthcheck.
- [#3922](https://github.com/thanos-io/thanos/pull/3922) Fix panic in http logging middleware.

### Changed

Expand Down
9 changes: 7 additions & 2 deletions pkg/logging/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ package logging

import (
"fmt"
"net"
"sort"
"strings"

"net/http"
"time"
Expand Down Expand Up @@ -39,7 +39,12 @@ func (m *HTTPServerMiddleware) HTTPMiddleware(name string, next http.Handler) ht
return func(w http.ResponseWriter, r *http.Request) {
wrapped := httputil.WrapResponseWriterWithStatus(w)
start := time.Now()
port := strings.Split(r.Host, ":")[1]
_, port, err := net.SplitHostPort(r.Host)
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(fmt.Sprintf("%s:%s", r.URL, port), nil)

Expand Down
37 changes: 37 additions & 0 deletions pkg/logging/http_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Copyright (c) The Thanos Authors.
// Licensed under the Apache License 2.0.

package logging

import (
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"

"github.com/go-kit/kit/log"
"github.com/thanos-io/thanos/pkg/testutil"
)

func TestHTTPServerMiddleware(t *testing.T) {
m := NewHTTPServerMiddleware(log.NewNopLogger())
handler := func(w http.ResponseWriter, r *http.Request) {
_, err := io.WriteString(w, "Test Works")
if err != nil {
t.Log(err)
}
}
hm := m.HTTPMiddleware("test", http.HandlerFunc(handler))

req := httptest.NewRequest("GET", "http://example.com/foo", nil)
w := httptest.NewRecorder()

hm(w, req)

resp := w.Result()
body, _ := ioutil.ReadAll(resp.Body)

testutil.Equals(t, 200, resp.StatusCode)
testutil.Equals(t, "Test Works", string(body))
}