Skip to content

Commit

Permalink
Implement debugging functionality when reading a response's body
Browse files Browse the repository at this point in the history
  • Loading branch information
shackra committed Dec 28, 2024
1 parent 0c9a018 commit c4af553
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 4 deletions.
41 changes: 41 additions & 0 deletions pkg/uhttp/body_print.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package uhttp

// Implements a debugging facility for request responses. This changes
// the behavior of `BaseHttpClient` with an unexported flag.
//
// If you always wanted to see the actual body of your response, now
// you can 👁️👄👁️undress it🫦 to uncover all its... data!

import (
"io"
"log"
)

type printReader struct {
reader io.Reader
}

func (pr *printReader) Read(p []byte) (int, error) {
n, err := pr.reader.Read(p)
if n > 0 {
log.Print(string(p[:n]))
}

return n, err
}

func wrapBodyToUndress(body io.Reader) io.Reader {
return &printReader{reader: body}
}

type undressOption struct {
undress bool
}

func (o undressOption) Apply(c *BaseHttpClient) {
c.debugPrintBody = o.undress
}

func WithUndressBody(undress bool) WrapperOption {
return undressOption{undress: undress}
}
13 changes: 9 additions & 4 deletions pkg/uhttp/wrapper.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,10 @@ type (
NewRequest(ctx context.Context, method string, url *url.URL, options ...RequestOption) (*http.Request, error)
}
BaseHttpClient struct {
HttpClient *http.Client
rateLimiter uRateLimit.Limiter
baseHttpCache icache
HttpClient *http.Client
rateLimiter uRateLimit.Limiter
baseHttpCache icache
debugPrintBody bool
}

DoOption func(resp *WrapperResponse) error
Expand Down Expand Up @@ -341,7 +342,11 @@ func (c *BaseHttpClient) Do(req *http.Request, options ...DoOption) (*http.Respo
}

// Replace resp.Body with a no-op closer so nobody has to worry about closing the reader.
resp.Body = io.NopCloser(bytes.NewBuffer(body))
if c.debugPrintBody {
resp.Body = io.NopCloser(wrapBodyToUndress(bytes.NewBuffer(body)))
} else {
resp.Body = io.NopCloser(bytes.NewBuffer(body))
}

wresp := WrapperResponse{
Header: resp.Header,
Expand Down

0 comments on commit c4af553

Please sign in to comment.