gitee.com/zhaochuninhefei/gmgo@v0.0.31-0.20240209061119-069254a02979/gmhttp/httptest/recorder.go (about) 1 // Copyright 2011 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package httptest 6 7 import ( 8 "bytes" 9 "fmt" 10 "io" 11 "net/textproto" 12 "strconv" 13 "strings" 14 15 http "gitee.com/zhaochuninhefei/gmgo/gmhttp" 16 17 "golang.org/x/net/http/httpguts" 18 ) 19 20 // ResponseRecorder is an implementation of http.ResponseWriter that 21 // records its mutations for later inspection in tests. 22 type ResponseRecorder struct { 23 // Code is the HTTP response code set by WriteHeader. 24 // 25 // Note that if a Handler never calls WriteHeader or Write, 26 // this might end up being 0, rather than the implicit 27 // http.StatusOK. To get the implicit value, use the Result 28 // method. 29 Code int 30 31 // HeaderMap contains the headers explicitly set by the Handler. 32 // It is an internal detail. 33 // 34 // ToDeprecated: HeaderMap exists for historical compatibility 35 // and should not be used. To access the headers returned by a handler, 36 // use the Response.Header map as returned by the Result method. 37 HeaderMap http.Header 38 39 // Body is the buffer to which the Handler's Write calls are sent. 40 // If nil, the Writes are silently discarded. 41 Body *bytes.Buffer 42 43 // Flushed is whether the Handler called Flush. 44 Flushed bool 45 46 result *http.Response // cache of Result's return value 47 snapHeader http.Header // snapshot of HeaderMap at first Write 48 wroteHeader bool 49 } 50 51 // NewRecorder returns an initialized ResponseRecorder. 52 func NewRecorder() *ResponseRecorder { 53 //goland:noinspection GoDeprecation 54 return &ResponseRecorder{ 55 HeaderMap: make(http.Header), 56 Body: new(bytes.Buffer), 57 Code: 200, 58 } 59 } 60 61 // DefaultRemoteAddr is the default remote address to return in RemoteAddr if 62 // an explicit DefaultRemoteAddr isn't set on ResponseRecorder. 63 //goland:noinspection GoUnusedConst 64 const DefaultRemoteAddr = "1.2.3.4" 65 66 // Header implements http.ResponseWriter. It returns the response 67 // headers to mutate within a handler. To test the headers that were 68 // written after a handler completes, use the Result method and see 69 // the returned Response value's Header. 70 func (rw *ResponseRecorder) Header() http.Header { 71 //goland:noinspection GoDeprecation 72 m := rw.HeaderMap 73 if m == nil { 74 m = make(http.Header) 75 //goland:noinspection GoDeprecation 76 rw.HeaderMap = m 77 } 78 return m 79 } 80 81 // writeHeader writes a header if it was not written yet and 82 // detects Content-Type if needed. 83 // 84 // bytes or str are the beginning of the response body. 85 // We pass both to avoid unnecessarily generate garbage 86 // in rw.WriteString which was created for performance reasons. 87 // Non-nil bytes win. 88 func (rw *ResponseRecorder) writeHeader(b []byte, str string) { 89 if rw.wroteHeader { 90 return 91 } 92 if len(str) > 512 { 93 str = str[:512] 94 } 95 96 m := rw.Header() 97 98 _, hasType := m["Content-Type"] 99 hasTE := m.Get("Transfer-Encoding") != "" 100 if !hasType && !hasTE { 101 if b == nil { 102 b = []byte(str) 103 } 104 m.Set("Content-Type", http.DetectContentType(b)) 105 } 106 107 rw.WriteHeader(200) 108 } 109 110 // Write implements http.ResponseWriter. The data in buf is written to 111 // rw.Body, if not nil. 112 func (rw *ResponseRecorder) Write(buf []byte) (int, error) { 113 rw.writeHeader(buf, "") 114 if rw.Body != nil { 115 rw.Body.Write(buf) 116 } 117 return len(buf), nil 118 } 119 120 // WriteString implements io.StringWriter. The data in str is written 121 // to rw.Body, if not nil. 122 func (rw *ResponseRecorder) WriteString(str string) (int, error) { 123 rw.writeHeader(nil, str) 124 if rw.Body != nil { 125 rw.Body.WriteString(str) 126 } 127 return len(str), nil 128 } 129 130 func checkWriteHeaderCode(code int) { 131 // Issue 22880: require valid WriteHeader status codes. 132 // For now we only enforce that it's three digits. 133 // In the future we might block things over 599 (600 and above aren't defined 134 // at https://httpwg.org/specs/rfc7231.html#status.codes) 135 // and we might block under 200 (once we have more mature 1xx support). 136 // But for now any three digits. 137 // 138 // We used to send "HTTP/1.1 000 0" on the wire in responses but there's 139 // no equivalent bogus thing we can realistically send in HTTP/2, 140 // so we'll consistently panic instead and help people find their bugs 141 // early. (We can't return an error from WriteHeader even if we wanted to.) 142 if code < 100 || code > 999 { 143 panic(fmt.Sprintf("invalid WriteHeader code %v", code)) 144 } 145 } 146 147 // WriteHeader implements http.ResponseWriter. 148 //goland:noinspection GoDeprecation 149 func (rw *ResponseRecorder) WriteHeader(code int) { 150 if rw.wroteHeader { 151 return 152 } 153 154 checkWriteHeaderCode(code) 155 rw.Code = code 156 rw.wroteHeader = true 157 if rw.HeaderMap == nil { 158 rw.HeaderMap = make(http.Header) 159 } 160 rw.snapHeader = rw.HeaderMap.Clone() 161 } 162 163 // Flush implements http.Flusher. To test whether Flush was 164 // called, see rw.Flushed. 165 func (rw *ResponseRecorder) Flush() { 166 if !rw.wroteHeader { 167 rw.WriteHeader(200) 168 } 169 rw.Flushed = true 170 } 171 172 // Result returns the response generated by the handler. 173 // 174 // The returned Response will have at least its StatusCode, 175 // Header, Body, and optionally Trailer populated. 176 // More fields may be populated in the future, so callers should 177 // not DeepEqual the result in tests. 178 // 179 // The Response.Header is a snapshot of the headers at the time of the 180 // first write call, or at the time of this call, if the handler never 181 // did a write. 182 // 183 // The Response.Body is guaranteed to be non-nil and Body.Read call is 184 // guaranteed to not return any error other than io.EOF. 185 // 186 // Result must only be called after the handler has finished running. 187 //goland:noinspection GoDeprecation 188 func (rw *ResponseRecorder) Result() *http.Response { 189 if rw.result != nil { 190 return rw.result 191 } 192 if rw.snapHeader == nil { 193 rw.snapHeader = rw.HeaderMap.Clone() 194 } 195 res := &http.Response{ 196 Proto: "HTTP/1.1", 197 ProtoMajor: 1, 198 ProtoMinor: 1, 199 StatusCode: rw.Code, 200 Header: rw.snapHeader, 201 } 202 rw.result = res 203 if res.StatusCode == 0 { 204 res.StatusCode = 200 205 } 206 res.Status = fmt.Sprintf("%03d %s", res.StatusCode, http.StatusText(res.StatusCode)) 207 if rw.Body != nil { 208 res.Body = io.NopCloser(bytes.NewReader(rw.Body.Bytes())) 209 } else { 210 res.Body = http.NoBody 211 } 212 res.ContentLength = parseContentLength(res.Header.Get("Content-Length")) 213 214 if trailers, ok := rw.snapHeader["Trailer"]; ok { 215 res.Trailer = make(http.Header, len(trailers)) 216 for _, k := range trailers { 217 k = http.CanonicalHeaderKey(k) 218 if !httpguts.ValidTrailerHeader(k) { 219 // Ignore since forbidden by RFC 7230, section 4.1.2. 220 continue 221 } 222 vv, ok := rw.HeaderMap[k] 223 if !ok { 224 continue 225 } 226 vv2 := make([]string, len(vv)) 227 copy(vv2, vv) 228 res.Trailer[k] = vv2 229 } 230 } 231 for k, vv := range rw.HeaderMap { 232 if !strings.HasPrefix(k, http.TrailerPrefix) { 233 continue 234 } 235 if res.Trailer == nil { 236 res.Trailer = make(http.Header) 237 } 238 for _, v := range vv { 239 res.Trailer.Add(strings.TrimPrefix(k, http.TrailerPrefix), v) 240 } 241 } 242 return res 243 } 244 245 // parseContentLength trims whitespace from s and returns -1 if no value 246 // is set, or the value if it's >= 0. 247 // 248 // This a modified version of same function found in net/http/transfer.go. This 249 // one just ignores an invalid header. 250 func parseContentLength(cl string) int64 { 251 cl = textproto.TrimString(cl) 252 if cl == "" { 253 return -1 254 } 255 n, err := strconv.ParseUint(cl, 10, 63) 256 if err != nil { 257 return -1 258 } 259 return int64(n) 260 }