Skip to content
This repository has been archived by the owner on Jun 21, 2024. It is now read-only.

Commit

Permalink
Merge pull request #295 from t0mk/http_json_indent
Browse files Browse the repository at this point in the history
Format and indent json from HTTP response body in debug mode
  • Loading branch information
displague committed Jul 12, 2021
2 parents d2f65e5 + 0732b6d commit 7736f04
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions packngo.go
Original file line number Diff line number Diff line change
Expand Up @@ -260,9 +260,22 @@ func dumpDeprecation(resp *http.Response) {
}
}

// from terraform-plugin-sdk/v2/helper/logging/transport.go
func prettyPrintJsonLines(b []byte) string {
parts := strings.Split(string(b), "\n")
for i, p := range parts {
if b := []byte(p); json.Valid(b) {
var out bytes.Buffer
_ = json.Indent(&out, b, "", " ")
parts[i] = out.String()
}
}
return strings.Join(parts, "\n")
}

func dumpResponse(resp *http.Response) {
o, _ := httputil.DumpResponse(resp, true)
strResp := string(o)
strResp := prettyPrintJsonLines(o)
reg, _ := regexp.Compile(`"token":(.+?),`)
reMatches := reg.FindStringSubmatch(strResp)
if len(reMatches) == 2 {
Expand All @@ -282,9 +295,9 @@ func dumpRequest(req *http.Request) {

o, _ := httputil.DumpRequestOut(r, false)
bbs, _ := ioutil.ReadAll(r.Body)

strReq := string(o)
log.Printf("\n=======[REQUEST]=============\n%s%s\n", string(strReq), string(bbs))
reqBodyStr := prettyPrintJsonLines(bbs)
strReq := prettyPrintJsonLines(o)
log.Printf("\n=======[REQUEST]=============\n%s%s\n", string(strReq), reqBodyStr)
}

// DoRequest is a convenience method, it calls NewRequest followed by Do
Expand Down

0 comments on commit 7736f04

Please sign in to comment.