Skip to content

Commit

Permalink
pkg/logging: Fix HTTP logging middleware panic (#3922)
Browse files Browse the repository at this point in the history
Signed-off-by: Frederic Branczyk <fbranczyk@gmail.com>
  • Loading branch information
brancz committed Mar 12, 2021
1 parent b2474aa commit fc9e30e
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 2 deletions.
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))
}

0 comments on commit fc9e30e

Please sign in to comment.