Skip to content

Commit

Permalink
feat: add /dump/request endpoint (#109)
Browse files Browse the repository at this point in the history
  • Loading branch information
chinaran authored Jan 31, 2023
1 parent 3a21fd7 commit f1f2de9
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 0 deletions.
15 changes: 15 additions & 0 deletions httpbin/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"encoding/json"
"fmt"
"net/http"
"net/http/httputil"
"net/url"
"sort"
"strconv"
Expand Down Expand Up @@ -1013,6 +1014,20 @@ func (h *HTTPBin) Base64(w http.ResponseWriter, r *http.Request) {
writeResponse(w, http.StatusOK, "text/plain", result)
}

// DumpRequest - returns the given request in its HTTP/1.x wire representation.
// The returned representation is an approximation only;
// some details of the initial request are lost while parsing it into
// an http.Request. In particular, the order and case of header field
// names are lost.
func (h *HTTPBin) DumpRequest(w http.ResponseWriter, r *http.Request) {
dump, err := httputil.DumpRequest(r, true)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(dump)
}

// JSON - returns a sample json
func (h *HTTPBin) JSON(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", jsonContentType)
Expand Down
13 changes: 13 additions & 0 deletions httpbin/handlers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2840,6 +2840,19 @@ func TestBase64(t *testing.T) {
}
}

func TestDumpRequest(t *testing.T) {
t.Parallel()
r, _ := http.NewRequest("GET", "/dump/request?foo=bar", nil)
r.Host = "test-host"
r.Header.Set("x-test-header2", "Test-Value2")
r.Header.Set("x-test-header1", "Test-Value1")
w := httptest.NewRecorder()
app.ServeHTTP(w, r)

assertContentType(t, w, "text/plain; charset=utf-8")
assertBodyEquals(t, w, "GET /dump/request?foo=bar HTTP/1.1\r\nHost: test-host\r\nX-Test-Header1: Test-Value1\r\nX-Test-Header2: Test-Value2\r\n\r\n")
}

func TestJSON(t *testing.T) {
t.Parallel()
r, _ := http.NewRequest("GET", "/json", nil)
Expand Down
2 changes: 2 additions & 0 deletions httpbin/httpbin.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,8 @@ func (h *HTTPBin) Handler() http.Handler {
mux.HandleFunc("/uuid", h.UUID)
mux.HandleFunc("/base64/", h.Base64)

mux.HandleFunc("/dump/request", h.DumpRequest)

// existing httpbin endpoints that we do not support
mux.HandleFunc("/brotli", notImplementedHandler)

Expand Down
9 changes: 9 additions & 0 deletions httpbin/static/index.html

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit f1f2de9

Please sign in to comment.