-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.go
114 lines (89 loc) · 2.33 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package awsmocker
import (
"bytes"
"fmt"
"io"
"net/http"
"net/http/httputil"
"time"
"github.com/google/uuid"
)
type httpResponse struct {
Header http.Header
StatusCode int
Body string
bodyRaw []byte
contentType string
extraHeaders map[string]string
forcedHttpResponse *http.Response
// isError bool
}
/*
func (hr *httpResponse) notifyIfError(m *mocker) *httpResponse {
if hr.isError {
m.t.Errorf("AWSMocker errored during the test")
}
return hr
}
*/
func (hr *httpResponse) toHttpResponse(req *http.Request) *http.Response {
if hr.forcedHttpResponse != nil {
return hr.forcedHttpResponse
}
resp := &http.Response{
ProtoMajor: req.ProtoMajor,
ProtoMinor: req.ProtoMinor,
Request: req,
TransferEncoding: req.TransferEncoding,
Header: hr.Header,
StatusCode: hr.StatusCode,
}
if resp.ProtoMajor == 0 {
resp.ProtoMajor = 1
}
if resp.Header == nil {
resp.Header = make(http.Header)
}
resp.Header.Add("Content-Type", hr.contentType)
resp.Header.Add("Server", "AWSMocker")
if hr.extraHeaders != nil && len(hr.extraHeaders) > 0 {
for k, v := range hr.extraHeaders {
resp.Header.Set(k, v)
}
}
if x := resp.Header.Get("Date"); x == "" {
resp.Header.Add("Date", time.Now().Format(http.TimeFormat))
}
if x := resp.Header.Get("X-Amzn-Requestid"); x == "" {
resp.Header.Add("X-Amzn-Requestid", generateRequestId())
}
resp.Status = http.StatusText(resp.StatusCode)
var buf *bytes.Buffer
if len(hr.bodyRaw) > 0 {
buf = bytes.NewBuffer(hr.bodyRaw)
} else {
buf = bytes.NewBufferString(hr.Body)
}
resp.ContentLength = int64(buf.Len())
resp.Body = io.NopCloser(buf)
if GlobalDebugMode {
fmt.Fprintln(DebugOutputWriter, "--- AWSMOCKER RESPONSE: -------------------------------")
dump, err := httputil.DumpResponse(resp, true)
if err == nil {
_, _ = DebugOutputWriter.Write(dump)
} else {
fmt.Fprintf(DebugOutputWriter, "FAILED TO DUMP RESPONSE!: %s", err)
}
fmt.Fprintln(DebugOutputWriter)
fmt.Fprintln(DebugOutputWriter, "-------------------------------------------------------")
}
return resp
}
// generate a request using a real UUID. if that fails, who cares this is a test
func generateRequestId() string {
id, err := uuid.NewRandom()
if err != nil {
return "1b206dd1-f9a8-11e5-becf-051c60f11c4a"
}
return id.String()
}