Skip to content

Instantly share code, notes, and snippets.

@ascarter
Created August 26, 2020 18:47
Show Gist options
  • Save ascarter/346754d7ff68ebfd9e9b86de6af02dfd to your computer and use it in GitHub Desktop.
Save ascarter/346754d7ff68ebfd9e9b86de6af02dfd to your computer and use it in GitHub Desktop.
package handlers
import (
"bytes"
"fmt"
"log"
"net/http"
"net/http/httptest"
"regexp"
"strings"
"testing"
)
var (
validLog = regexp.MustCompile(`(\d.\d.\d.\d) - - \[(\d{2}[/]\d{2}[/]\d{4}:\d{2}:\d{2}:\d{2} [-+]\d{4})\]\s"GET\s.*\sHTTP/1.1"\s200`)
)
func TestLogHandler(t *testing.T) {
expected := "Hello client"
// Capture logging
var b bytes.Buffer
logger := log.New(&b, "", 0)
fn := func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, expected)
}
h := RequestLogHandler(http.HandlerFunc(fn), logger)
req, err := http.NewRequest("GET", "http://example.com/foo", nil)
if err != nil {
t.Fatal(err)
}
// Set a request address for the test
raddr := "127.0.0.1"
req.Header.Set("X-Forwarded-For", raddr)
w := httptest.NewRecorder()
h.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("%d != %d", w.Code, http.StatusOK)
}
body := strings.TrimSpace(w.Body.String())
if body != expected {
t.Errorf("%s != %s", body, expected)
}
messages := strings.FieldsFunc(b.String(), func(c rune) bool {
return c == '\n'
})
if len(messages) != 1 {
t.Fatalf("Expected %d messages but got %d: %q", 1, len(messages), messages)
}
if !validLog.MatchString(messages[0]) {
t.Errorf("%q not valid log message format", messages[0])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment