Commit fdad616d authored by Matt Holt's avatar Matt Holt Committed by GitHub

Merge pull request #1049 from tw4452852/log_body

capture request body normally
parents 1d3212a5 590862a9
This diff is collapsed.
package httpserver package httpserver
import ( import (
"bytes"
"io/ioutil"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"os" "os"
...@@ -24,28 +22,12 @@ func TestNewReplacer(t *testing.T) { ...@@ -24,28 +22,12 @@ func TestNewReplacer(t *testing.T) {
switch v := rep.(type) { switch v := rep.(type) {
case *replacer: case *replacer:
if v.replacements["{host}"]() != "localhost" { if v.getSubstitution("{host}") != "localhost" {
t.Error("Expected host to be localhost") t.Error("Expected host to be localhost")
} }
if v.replacements["{method}"]() != "POST" { if v.getSubstitution("{method}") != "POST" {
t.Error("Expected request method to be POST") t.Error("Expected request method to be POST")
} }
// Response placeholders should only be set after call to Replace()
got, want := "", ""
if getReplacement, ok := v.replacements["{status}"]; ok {
got = getReplacement()
}
if want := ""; got != want {
t.Errorf("Expected status to NOT be set before Replace() is called; was: %s", got)
}
rep.Replace("{foobar}")
if getReplacement, ok := v.replacements["{status}"]; ok {
got = getReplacement()
}
if want = "200"; got != want {
t.Errorf("Expected status to be %s, was: %s", want, got)
}
default: default:
t.Fatalf("Expected *replacer underlying Replacer type, got: %#v", rep) t.Fatalf("Expected *replacer underlying Replacer type, got: %#v", rep)
} }
...@@ -94,19 +76,21 @@ func TestReplace(t *testing.T) { ...@@ -94,19 +76,21 @@ func TestReplace(t *testing.T) {
complexCases := []struct { complexCases := []struct {
template string template string
replacements map[string]func() string replacements map[string]string
expect string expect string
}{ }{
{"/a{1}/{2}", {
map[string]func() string{ "/a{1}/{2}",
"{1}": func() string { return "12" }, map[string]string{
"{2}": func() string { return "" }}, "{1}": "12",
"{2}": "",
},
"/a12/"}, "/a12/"},
} }
for _, c := range complexCases { for _, c := range complexCases {
repl := &replacer{ repl := &replacer{
replacements: c.replacements, customReplacements: c.replacements,
} }
if expected, actual := c.expect, repl.Replace(c.template); expected != actual { if expected, actual := c.expect, repl.Replace(c.template); expected != actual {
t.Errorf("for template '%s', expected '%s', got '%s'", c.template, expected, actual) t.Errorf("for template '%s', expected '%s', got '%s'", c.template, expected, actual)
...@@ -163,28 +147,3 @@ func TestRound(t *testing.T) { ...@@ -163,28 +147,3 @@ func TestRound(t *testing.T) {
} }
} }
} }
func TestReadRequestBody(t *testing.T) {
payload := []byte(`{ "foo": "bar" }`)
var readSize int64 = 5
r, err := http.NewRequest("POST", "/", bytes.NewReader(payload))
if err != nil {
t.Error(err)
}
defer r.Body.Close()
logBody, err := readRequestBody(r, readSize)
if err != nil {
t.Error("readRequestBody failed", err)
} else if !bytes.EqualFold(payload[0:readSize], logBody) {
t.Error("Expected log comparison failed")
}
// Ensure the Request body is the same as the original.
reqBody, err := ioutil.ReadAll(r.Body)
if err != nil {
t.Error("Unable to read request body", err)
} else if !bytes.EqualFold(payload, reqBody) {
t.Error("Expected request body comparison failed")
}
}
...@@ -2,6 +2,7 @@ package log ...@@ -2,6 +2,7 @@ package log
import ( import (
"bytes" "bytes"
"io/ioutil"
"log" "log"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
...@@ -60,3 +61,59 @@ func TestLoggedStatus(t *testing.T) { ...@@ -60,3 +61,59 @@ func TestLoggedStatus(t *testing.T) {
t.Errorf("Expected the log entry to contain 'foobar' (custom placeholder), but it didn't: %s", logged) t.Errorf("Expected the log entry to contain 'foobar' (custom placeholder), but it didn't: %s", logged)
} }
} }
func TestLogRequestBody(t *testing.T) {
var got bytes.Buffer
logger := Logger{
Rules: []Rule{{
PathScope: "/",
Format: "{request_body}",
Log: log.New(&got, "", 0),
}},
Next: httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
// drain up body
ioutil.ReadAll(r.Body)
return 0, nil
}),
}
for i, c := range []struct {
body string
expect string
}{
{"", "\n"},
{"{hello} world!", "{hello} world!\n"},
{func() string {
length := httpserver.MaxLogBodySize + 100
b := make([]byte, length)
for i := 0; i < length; i++ {
b[i] = 0xab
}
return string(b)
}(), func() string {
b := make([]byte, httpserver.MaxLogBodySize)
for i := 0; i < httpserver.MaxLogBodySize; i++ {
b[i] = 0xab
}
return string(b) + "\n"
}(),
},
} {
got.Reset()
r, err := http.NewRequest("POST", "/", bytes.NewBufferString(c.body))
if err != nil {
t.Fatal(err)
}
r.Header.Set("Content-Type", "application/json")
status, err := logger.ServeHTTP(httptest.NewRecorder(), r)
if status != 0 {
t.Errorf("case %d: Expected status to be 0, but was %d", i, status)
}
if err != nil {
t.Errorf("case %d: Expected error to be nil, instead got: %v", i, err)
}
if got.String() != c.expect {
t.Errorf("case %d: Expected body %q, but got %q", i, c.expect, got.String())
}
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment