github.com/webdestroya/awsmocker@v0.2.6/response.go (about) 1 package awsmocker 2 3 import ( 4 "bytes" 5 "fmt" 6 "io" 7 "net/http" 8 "net/http/httputil" 9 "time" 10 11 "github.com/google/uuid" 12 ) 13 14 type httpResponse struct { 15 Header http.Header 16 StatusCode int 17 Body string 18 19 bodyRaw []byte 20 21 contentType string 22 23 extraHeaders map[string]string 24 25 forcedHttpResponse *http.Response 26 27 // isError bool 28 } 29 30 /* 31 func (hr *httpResponse) notifyIfError(m *mocker) *httpResponse { 32 if hr.isError { 33 m.t.Errorf("AWSMocker errored during the test") 34 } 35 return hr 36 } 37 */ 38 39 func (hr *httpResponse) toHttpResponse(req *http.Request) *http.Response { 40 41 if hr.forcedHttpResponse != nil { 42 return hr.forcedHttpResponse 43 } 44 45 resp := &http.Response{ 46 ProtoMajor: req.ProtoMajor, 47 ProtoMinor: req.ProtoMinor, 48 Request: req, 49 TransferEncoding: req.TransferEncoding, 50 Header: hr.Header, 51 StatusCode: hr.StatusCode, 52 } 53 54 if resp.ProtoMajor == 0 { 55 resp.ProtoMajor = 1 56 } 57 58 if resp.Header == nil { 59 resp.Header = make(http.Header) 60 } 61 62 resp.Header.Add("Content-Type", hr.contentType) 63 resp.Header.Add("Server", "AWSMocker") 64 65 if hr.extraHeaders != nil && len(hr.extraHeaders) > 0 { 66 for k, v := range hr.extraHeaders { 67 resp.Header.Set(k, v) 68 } 69 } 70 71 if x := resp.Header.Get("Date"); x == "" { 72 resp.Header.Add("Date", time.Now().Format(http.TimeFormat)) 73 } 74 75 if x := resp.Header.Get("X-Amzn-Requestid"); x == "" { 76 resp.Header.Add("X-Amzn-Requestid", generateRequestId()) 77 } 78 79 resp.Status = http.StatusText(resp.StatusCode) 80 81 var buf *bytes.Buffer 82 if len(hr.bodyRaw) > 0 { 83 buf = bytes.NewBuffer(hr.bodyRaw) 84 } else { 85 buf = bytes.NewBufferString(hr.Body) 86 } 87 88 resp.ContentLength = int64(buf.Len()) 89 resp.Body = io.NopCloser(buf) 90 91 if GlobalDebugMode { 92 fmt.Fprintln(DebugOutputWriter, "--- AWSMOCKER RESPONSE: -------------------------------") 93 dump, err := httputil.DumpResponse(resp, true) 94 if err == nil { 95 _, _ = DebugOutputWriter.Write(dump) 96 } else { 97 fmt.Fprintf(DebugOutputWriter, "FAILED TO DUMP RESPONSE!: %s", err) 98 } 99 fmt.Fprintln(DebugOutputWriter) 100 fmt.Fprintln(DebugOutputWriter, "-------------------------------------------------------") 101 } 102 103 return resp 104 } 105 106 // generate a request using a real UUID. if that fails, who cares this is a test 107 func generateRequestId() string { 108 id, err := uuid.NewRandom() 109 if err != nil { 110 return "1b206dd1-f9a8-11e5-becf-051c60f11c4a" 111 } 112 113 return id.String() 114 }