forked from tomnomnom/meg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.go
91 lines (69 loc) · 1.67 KB
/
response.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"bytes"
"crypto/sha1"
"fmt"
"io/ioutil"
"os"
"path"
)
// a response is a wrapper around an HTTP response;
// it contains the request value for context.
type response struct {
request request
status string
statusCode int
headers []string
body []byte
err error
}
// String returns a string representation of the request and response
func (r response) String() string {
b := &bytes.Buffer{}
b.WriteString(r.request.URL())
b.WriteString("\n\n")
b.WriteString(fmt.Sprintf("> %s %s HTTP/1.1\n", r.request.method, r.request.path))
// request headers
for _, h := range r.request.headers {
b.WriteString(fmt.Sprintf("> %s\n", h))
}
b.WriteString("\n")
// status line
b.WriteString(fmt.Sprintf("< HTTP/1.1 %s\n", r.status))
// response headers
for _, h := range r.headers {
b.WriteString(fmt.Sprintf("< %s\n", h))
}
b.WriteString("\n")
// body
b.Write(r.body)
return b.String()
}
func (r response) StringNoHeaders() string {
b := &bytes.Buffer{}
b.Write(r.body)
return b.String()
}
// save write a request and response output to disk
func (r response) save(pathPrefix string, noHeaders bool) (string, error) {
content := []byte(r.String())
if noHeaders {
content = []byte(r.StringNoHeaders())
}
checksum := sha1.Sum(content)
parts := []string{pathPrefix}
parts = append(parts, r.request.Hostname())
parts = append(parts, fmt.Sprintf("%x", checksum))
p := path.Join(parts...)
if _, err := os.Stat(path.Dir(p)); os.IsNotExist(err) {
err = os.MkdirAll(path.Dir(p), 0750)
if err != nil {
return p, err
}
}
err := ioutil.WriteFile(p, content, 0640)
if err != nil {
return p, err
}
return p, nil
}