X Tutup
Skip to content

Commit 0b0fd42

Browse files
committed
Dump HTTP request/response bodies when DEBUG=api
1 parent 50a8956 commit 0b0fd42

File tree

2 files changed

+24
-3
lines changed

2 files changed

+24
-3
lines changed

api/client.go

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ import (
77
"io"
88
"io/ioutil"
99
"net/http"
10+
"regexp"
11+
"strings"
1012
)
1113

1214
// ClientOption represents an argument to NewClient
@@ -34,13 +36,26 @@ func AddHeader(name, value string) ClientOption {
3436
}
3537

3638
// VerboseLog enables request/response logging within a RoundTripper
37-
func VerboseLog(out io.Writer) ClientOption {
39+
func VerboseLog(out io.Writer, logBodies bool) ClientOption {
3840
return func(tr http.RoundTripper) http.RoundTripper {
3941
return &funcTripper{roundTrip: func(req *http.Request) (*http.Response, error) {
4042
fmt.Fprintf(out, "> %s %s\n", req.Method, req.URL.RequestURI())
43+
if logBodies && req.Body != nil && inspectableMIMEType(req.Header.Get("Content-type")) {
44+
newBody := &bytes.Buffer{}
45+
io.Copy(out, io.TeeReader(req.Body, newBody))
46+
fmt.Fprintln(out)
47+
req.Body = ioutil.NopCloser(newBody)
48+
}
4149
res, err := tr.RoundTrip(req)
4250
if err == nil {
4351
fmt.Fprintf(out, "< HTTP %s\n", res.Status)
52+
if logBodies && res.Body != nil && inspectableMIMEType(res.Header.Get("Content-type")) {
53+
newBody := &bytes.Buffer{}
54+
// TODO: pretty-print response JSON
55+
io.Copy(out, io.TeeReader(res.Body, newBody))
56+
fmt.Fprintln(out)
57+
res.Body = ioutil.NopCloser(newBody)
58+
}
4459
}
4560
return res, err
4661
}}
@@ -179,3 +194,9 @@ func handleHTTPError(resp *http.Response) error {
179194

180195
return fmt.Errorf("http error, '%s' failed (%d): '%s'", resp.Request.URL, resp.StatusCode, message)
181196
}
197+
198+
var jsonTypeRE = regexp.MustCompile(`[/+]json($|;)`)
199+
200+
func inspectableMIMEType(t string) bool {
201+
return strings.HasPrefix(t, "text/") || jsonTypeRE.MatchString(t)
202+
}

command/root.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ func BasicClient() (*api.Client, error) {
8484
opts = append(opts, api.AddHeader("Authorization", fmt.Sprintf("token %s", c.Token)))
8585
}
8686
if verbose := os.Getenv("DEBUG"); verbose != "" {
87-
opts = append(opts, api.VerboseLog(os.Stderr))
87+
opts = append(opts, api.VerboseLog(os.Stderr, false))
8888
}
8989
return api.NewClient(opts...), nil
9090
}
@@ -113,7 +113,7 @@ var apiClientForContext = func(ctx context.Context) (*api.Client, error) {
113113
api.AddHeader("GraphQL-Features", "pe_mobile"),
114114
}
115115
if verbose := os.Getenv("DEBUG"); verbose != "" {
116-
opts = append(opts, api.VerboseLog(os.Stderr))
116+
opts = append(opts, api.VerboseLog(os.Stderr, strings.Contains(verbose, "api")))
117117
}
118118
return api.NewClient(opts...), nil
119119
}

0 commit comments

Comments
 (0)
X Tutup