Source file src/pkg/net/http/httptest/recorder.go
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 provides utilities for HTTP testing. 6 package httptest 7 8 import ( 9 "bytes" 10 "net/http" 11 ) 12 13 // ResponseRecorder is an implementation of http.ResponseWriter that 14 // records its mutations for later inspection in tests. 15 type ResponseRecorder struct { 16 Code int // the HTTP response code from WriteHeader 17 HeaderMap http.Header // the HTTP response headers 18 Body *bytes.Buffer // if non-nil, the bytes.Buffer to append written data to 19 Flushed bool 20 } 21 22 // NewRecorder returns an initialized ResponseRecorder. 23 func NewRecorder() *ResponseRecorder { 24 return &ResponseRecorder{ 25 HeaderMap: make(http.Header), 26 Body: new(bytes.Buffer), 27 } 28 } 29 30 // DefaultRemoteAddr is the default remote address to return in RemoteAddr if 31 // an explicit DefaultRemoteAddr isn't set on ResponseRecorder. 32 const DefaultRemoteAddr = "1.2.3.4" 33 34 // Header returns the response headers. 35 func (rw *ResponseRecorder) Header() http.Header { 36 return rw.HeaderMap 37 } 38 39 // Write always succeeds and writes to rw.Body, if not nil. 40 func (rw *ResponseRecorder) Write(buf []byte) (int, error) { 41 if rw.Body != nil { 42 rw.Body.Write(buf) 43 } 44 if rw.Code == 0 { 45 rw.Code = http.StatusOK 46 } 47 return len(buf), nil 48 } 49 50 // WriteHeader sets rw.Code. 51 func (rw *ResponseRecorder) WriteHeader(code int) { 52 rw.Code = code 53 } 54 55 // Flush sets rw.Flushed to true. 56 func (rw *ResponseRecorder) Flush() { 57 rw.Flushed = true 58 }