diff --git a/cmd/utils.go b/cmd/utils.go index 5de27f5a0..ab194d189 100644 --- a/cmd/utils.go +++ b/cmd/utils.go @@ -18,6 +18,7 @@ package cmd import ( "encoding/base64" + "encoding/json" "encoding/xml" "errors" "fmt" @@ -28,8 +29,6 @@ import ( "strings" "time" - "encoding/json" - humanize "github.com/dustin/go-humanize" "github.com/pkg/profile" ) @@ -248,12 +247,15 @@ func dumpRequest(r *http.Request) string { Path string `json:"path"` Query string `json:"query"` Header http.Header `json:"header"` - }{r.Method, r.URL.Path, r.URL.RawQuery, header} - jsonBytes, err := json.Marshal(req) + }{r.Method, getURLEncodedName(r.URL.Path), r.URL.RawQuery, header} + jsonBytes, err := json.Marshal(&req) if err != nil { - return "" + // Upon error just return Go-syntax representation of the value + return fmt.Sprintf("%#v", req) } - return string(jsonBytes) + // Replace all '%' to '%%' so that printer format parser + // to ignore URL encoded values. + return strings.Replace(string(jsonBytes), "%", "%%", -1) } // isFile - returns whether given path is a file or not. diff --git a/cmd/utils_test.go b/cmd/utils_test.go index f8a241fc2..360572df9 100644 --- a/cmd/utils_test.go +++ b/cmd/utils_test.go @@ -17,12 +17,14 @@ package cmd import ( + "encoding/json" "fmt" "net" "net/http" "net/url" "reflect" "runtime" + "strings" "testing" ) @@ -413,3 +415,44 @@ func TestCheckURL(t *testing.T) { } } } + +// Testing dumping request function. +func TestDumpRequest(t *testing.T) { + req, err := http.NewRequest("GET", "http://localhost:9000?prefix=Hello%2AWorld%2A", nil) + if err != nil { + t.Fatal(err) + } + req.Header.Set("content-md5", "====test") + jsonReq := dumpRequest(req) + type jsonResult struct { + Method string `json:"method"` + Path string `json:"path"` + Query string `json:"query"` + Header http.Header `json:"header"` + } + jsonReq = strings.Replace(jsonReq, "%%", "%", -1) + res := jsonResult{} + if err = json.Unmarshal([]byte(jsonReq), &res); err != nil { + t.Fatal(err) + } + + // Look for expected method. + if res.Method != "GET" { + t.Fatalf("Unexpected method %s, expected 'GET'", res.Method) + } + + // Look for expected query values + expectedQuery := url.Values{} + expectedQuery.Set("prefix", "Hello*World*") + if !reflect.DeepEqual(res.Query, expectedQuery.Encode()) { + t.Fatalf("Expected %#v, got %#v", expectedQuery, res.Query) + } + + // Look for expected header. + expectedHeader := http.Header{} + expectedHeader.Set("content-md5", "====test") + expectedHeader.Set("host", "localhost:9000") + if !reflect.DeepEqual(res.Header, expectedHeader) { + t.Fatalf("Expected %#v, got %#v", expectedHeader, res.Header) + } +}