forked from qustavo/httplab
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dump.go
73 lines (59 loc) · 1.32 KB
/
dump.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package httplab
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"regexp"
"strings"
)
var decolorizeRegex = regexp.MustCompile("\x1b\\[0;\\d+m")
func Decolorize(s []byte) []byte {
return decolorizeRegex.ReplaceAll(s, nil)
}
func valueOrDefault(value, def string) string {
if value == "" {
return def
}
return value
}
func withColor(color int, text string) string {
return fmt.Sprintf("\x1b[0;%dm%s\x1b[0;0m", color, text)
}
func writeBody(buf *bytes.Buffer, req *http.Request) error {
body, err := ioutil.ReadAll(req.Body)
if err != nil {
return err
}
if len(body) > 0 {
buf.WriteRune('\n')
}
if strings.Contains(req.Header.Get("Content-Type"), "application/json") {
if err := json.Indent(buf, body, "", " "); err == nil {
return nil
}
}
_, err = buf.Write(body)
return err
}
func DumpRequest(req *http.Request) ([]byte, error) {
buf := bytes.NewBuffer(nil)
reqURI := req.RequestURI
if reqURI == "" {
reqURI = req.URL.RequestURI()
}
fmt.Fprintf(buf, "%s %s %s/%d.%d\n",
withColor(35, valueOrDefault(req.Method, "GET")),
reqURI,
withColor(35, "HTTP"),
req.ProtoMajor,
req.ProtoMinor,
)
for key := range req.Header {
val := req.Header.Get(key)
fmt.Fprintf(buf, "%s: %s\n", withColor(31, key), withColor(32, val))
}
err := writeBody(buf, req)
return buf.Bytes(), err
}