Skip to content
Open
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
18 changes: 17 additions & 1 deletion dump.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ package httplab

import (
"bytes"
"compress/gzip"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"regexp"
"sort"
"strings"
"io"
)

var decolorizeRegex = regexp.MustCompile("\x1b\\[0;\\d+m")
Expand All @@ -29,6 +31,19 @@ func withColor(color int, text string) string {
}

func writeBody(buf *bytes.Buffer, req *http.Request) error {
ctype := req.Header.Get("Content-Type")

// Decoding Gzipped content
if strings.Contains(ctype, "gzip") {
raw, err := gzip.NewReader(req.Body)
if err != nil {
return err
}

_, err = io.Copy(buf, raw)
return err
}

body, err := ioutil.ReadAll(req.Body)
if err != nil {
return err
Expand All @@ -38,7 +53,8 @@ func writeBody(buf *bytes.Buffer, req *http.Request) error {
buf.WriteRune('\n')
}

if strings.Contains(req.Header.Get("Content-Type"), "application/json") {
// JSON stuff
if strings.Contains(ctype, "application/json") {
if err := json.Indent(buf, body, "", " "); err == nil {
return nil
}
Expand Down
31 changes: 29 additions & 2 deletions dump_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ package httplab

import (
"bytes"
"compress/gzip"
"fmt"
"net/http"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"strings"
"sort"
"strings"
)

func TestDumpRequestWithJSON(t *testing.T) {
Expand All @@ -34,6 +35,32 @@ func TestDumpRequestWithJSON(t *testing.T) {
require.NoError(t, err)
fmt.Printf("%s\n", buf)
})

t.Run("Gzip", func(t *testing.T) {
var gzbuf bytes.Buffer
gz := gzip.NewWriter(&gzbuf)
gz.Write([]byte(`{"foo": "bar", "a": [1,2,3]}`))
gz.Close()

req, _ := http.NewRequest("GET", "/withJSON", &gzbuf)
req.Header.Set("Content-Type", "gzip")

buf, err := DumpRequest(req)
require.NoError(t, err)
require.True(t, strings.Contains(string(buf), `"foo": "bar"`))
fmt.Printf("%s\n", buf)
})

t.Run("Invalid Gzip", func(t *testing.T) {
req, _ := http.NewRequest("GET", "/withJSON", bytes.NewBuffer(
[]byte(`This is not a gzip`),
))
req.Header.Set("Content-Type", "gzip")

buf, err := DumpRequest(req)
require.Error(t, err)
fmt.Printf("%s\n", buf)
})
}

func TestDumpRequestHeaders(t *testing.T) {
Expand All @@ -50,7 +77,7 @@ func TestDumpRequestHeaders(t *testing.T) {
sort.Strings(keys)

startLine := "GET / HTTP/1.1\n"
response := startLine + strings.Join(keys, ": \n") + ": \n"
response := startLine + strings.Join(keys, ": \n") + ": \n"

assert.Contains(t, response, string(Decolorize(buf)))
})
Expand Down