| 1 |
// Copyright (c) 2021, Maxime Soulé |
| 2 |
// All rights reserved. |
| 3 |
// |
| 4 |
// This source code is licensed under the BSD-style license found in the |
| 5 |
// LICENSE file in the root directory of this source tree. |
| 6 |
|
| 7 |
package internal |
| 8 |
|
| 9 |
import ( |
| 10 |
"bytes" |
| 11 |
"net/http" |
| 12 |
"net/http/httputil" |
| 13 |
"testing" |
| 14 |
"unicode/utf8" |
| 15 |
) |
| 16 |
|
| 17 |
// canBackquote is the same as strconv.CanBackquote but works on |
| 18 |
// []byte and accepts '\n' and '\r'. |
| 19 |
func canBackquote(b []byte) bool { |
| 20 |
for len(b) > 0 { |
| 21 |
r, wid := utf8.DecodeRune(b) |
| 22 |
b = b[wid:] |
| 23 |
if wid > 1 { |
| 24 |
if r == '\ufeff' { |
| 25 |
return false // BOMs are invisible and should not be quoted. |
| 26 |
} |
| 27 |
continue // All other multibyte runes are correctly encoded and assumed printable. |
| 28 |
} |
| 29 |
if r == utf8.RuneError { |
| 30 |
return false |
| 31 |
} |
| 32 |
if (r < ' ' && r != '\t' && r != '\n' && r != '\r') || r == '`' || r == '\u007F' { |
| 33 |
return false |
| 34 |
} |
| 35 |
} |
| 36 |
return true |
| 37 |
} |
| 38 |
|
| 39 |
func replaceCrLf(b []byte) []byte { |
| 40 |
return bytes.ReplaceAll(b, []byte("\r\n"), []byte("\n")) |
| 41 |
} |
| 42 |
|
| 43 |
func backquote(b []byte) ([]byte, bool) { |
| 44 |
// if there is as many \r\n as \n, replace all occurrences by \n |
| 45 |
// so we can conveniently print the buffer inside `…`. |
| 46 |
crnl := bytes.Count(b, []byte("\r\n")) |
| 47 |
cr := bytes.Count(b, []byte("\r")) |
| 48 |
if crnl != 0 { |
| 49 |
nl := bytes.Count(b, []byte("\n")) |
| 50 |
if crnl != nl || crnl != cr { |
| 51 |
return nil, false |
| 52 |
} |
| 53 |
return replaceCrLf(b), true |
| 54 |
} |
| 55 |
|
| 56 |
return b, cr == 0 |
| 57 |
} |
| 58 |
|
| 59 |
// DumpResponse logs "resp" using Logf method of "t". |
| 60 |
// |
| 61 |
// It tries to produce a result as readable as possible first using |
| 62 |
// backquotes then falling back to double-quotes. |
| 63 |
func DumpResponse(t testing.TB, resp *http.Response) { |
| 64 |
t.Helper() |
| 65 |
|
| 66 |
const label = "Received response:\n" |
| 67 |
b, _ := httputil.DumpResponse(resp, true) |
| 68 |
if canBackquote(b) { |
| 69 |
bodyPos := bytes.Index(b, []byte("\r\n\r\n")) |
| 70 |
|
| 71 |
if body, ok := backquote(b[bodyPos+4:]); ok { |
| 72 |
headers := replaceCrLf(b[:bodyPos]) |
| 73 |
t.Logf(label+"`%s\n\n%s`", headers, body) |
| 74 |
return |
| 75 |
} |
| 76 |
} |
| 77 |
|
| 78 |
t.Logf(label+"%q", b) |
| 79 |
} |