Result returns the response generated by the handler. The returned Response will have at least its StatusCode, Header, Body, and optionally Trailer populated. More fields may be populated in the future, so callers should not DeepEqual the result in tests. The Response.Header is a snapshot of the h
()
| 199 | // |
| 200 | // Result must only be called after the handler has finished running. |
| 201 | func (rw *ResponseRecorder) Result() *http.Response { |
| 202 | if rw.result != nil { |
| 203 | return rw.result |
| 204 | } |
| 205 | if rw.snapHeader == nil { |
| 206 | rw.snapHeader = rw.HeaderMap.Clone() |
| 207 | } |
| 208 | res := &http.Response{ |
| 209 | Proto: "HTTP/1.1", |
| 210 | ProtoMajor: 1, |
| 211 | ProtoMinor: 1, |
| 212 | StatusCode: rw.Code, |
| 213 | Header: rw.snapHeader, |
| 214 | } |
| 215 | rw.result = res |
| 216 | if res.StatusCode == 0 { |
| 217 | res.StatusCode = 200 |
| 218 | } |
| 219 | res.Status = fmt.Sprintf("%03d %s", res.StatusCode, http.StatusText(res.StatusCode)) |
| 220 | if rw.Body != nil { |
| 221 | res.Body = io.NopCloser(bytes.NewReader(rw.Body.Bytes())) |
| 222 | } else { |
| 223 | res.Body = http.NoBody |
| 224 | } |
| 225 | res.ContentLength = parseContentLength(res.Header.Get("Content-Length")) |
| 226 | |
| 227 | if trailers, ok := rw.snapHeader["Trailer"]; ok { |
| 228 | res.Trailer = make(http.Header, len(trailers)) |
| 229 | for _, k := range trailers { |
| 230 | for k := range strings.SplitSeq(k, ",") { |
| 231 | k = http.CanonicalHeaderKey(textproto.TrimString(k)) |
| 232 | if !httpguts.ValidTrailerHeader(k) { |
| 233 | // Ignore since forbidden by RFC 7230, section 4.1.2. |
| 234 | continue |
| 235 | } |
| 236 | vv, ok := rw.HeaderMap[k] |
| 237 | if !ok { |
| 238 | continue |
| 239 | } |
| 240 | vv2 := make([]string, len(vv)) |
| 241 | copy(vv2, vv) |
| 242 | res.Trailer[k] = vv2 |
| 243 | } |
| 244 | } |
| 245 | } |
| 246 | for k, vv := range rw.HeaderMap { |
| 247 | if !strings.HasPrefix(k, http.TrailerPrefix) { |
| 248 | continue |
| 249 | } |
| 250 | if res.Trailer == nil { |
| 251 | res.Trailer = make(http.Header) |
| 252 | } |
| 253 | for _, v := range vv { |
| 254 | res.Trailer.Add(strings.TrimPrefix(k, http.TrailerPrefix), v) |
| 255 | } |
| 256 | } |
| 257 | return res |
| 258 | } |
no test coverage detected