github.com/thanos-io/thanos@v0.32.5/pkg/logging/http_test.go (about)

     1  // Copyright (c) The Thanos Authors.
     2  // Licensed under the Apache License 2.0.
     3  
     4  package logging
     5  
     6  import (
     7  	"bytes"
     8  	"io"
     9  	"net/http"
    10  	"net/http/httptest"
    11  	"net/url"
    12  	"strings"
    13  	"testing"
    14  
    15  	"github.com/go-kit/log"
    16  
    17  	"github.com/efficientgo/core/testutil"
    18  )
    19  
    20  func TestHTTPServerMiddleware(t *testing.T) {
    21  	b := bytes.Buffer{}
    22  
    23  	m := NewHTTPServerMiddleware(log.NewLogfmtLogger(io.Writer(&b)))
    24  	handler := func(w http.ResponseWriter, r *http.Request) {
    25  		_, err := io.WriteString(w, "Test Works")
    26  		if err != nil {
    27  			testutil.Ok(t, err)
    28  		}
    29  	}
    30  	hm := m.HTTPMiddleware("test", http.HandlerFunc(handler))
    31  
    32  	// Regression test for Cortex way - https://github.com/thanos-io/thanos/pull/4041
    33  	u, err := url.Parse("http://example.com:5555/foo")
    34  	testutil.Ok(t, err)
    35  	req := &http.Request{
    36  		Method: "GET",
    37  		URL:    u,
    38  		Body:   nil,
    39  	}
    40  
    41  	w := httptest.NewRecorder()
    42  
    43  	hm(w, req)
    44  
    45  	resp := w.Result()
    46  	body, err := io.ReadAll(resp.Body)
    47  	testutil.Ok(t, err)
    48  
    49  	testutil.Equals(t, 200, resp.StatusCode)
    50  	testutil.Equals(t, "Test Works", string(body))
    51  	testutil.Assert(t, !strings.Contains(b.String(), "err="))
    52  
    53  	// Typical way:
    54  	req = httptest.NewRequest("GET", "http://example.com:5555/foo", nil)
    55  	b.Reset()
    56  
    57  	w = httptest.NewRecorder()
    58  	hm(w, req)
    59  
    60  	resp = w.Result()
    61  	body, err = io.ReadAll(resp.Body)
    62  	testutil.Ok(t, err)
    63  
    64  	testutil.Equals(t, 200, resp.StatusCode)
    65  	testutil.Equals(t, "Test Works", string(body))
    66  	testutil.Assert(t, !strings.Contains(b.String(), "err="))
    67  
    68  	// URL with no explicit port number in the format- hostname:port
    69  	req = httptest.NewRequest("GET", "http://example.com/foo", nil)
    70  	b.Reset()
    71  
    72  	w = httptest.NewRecorder()
    73  	hm(w, req)
    74  
    75  	resp = w.Result()
    76  	body, err = io.ReadAll(resp.Body)
    77  	testutil.Ok(t, err)
    78  
    79  	testutil.Equals(t, 200, resp.StatusCode)
    80  	testutil.Equals(t, "Test Works", string(body))
    81  	testutil.Assert(t, !strings.Contains(b.String(), "err="))
    82  }