blob: f69279f7c1c037c94e0ceef9099508cd402778d4 [file] [log] [blame]
Brad Fitzpatrickda679db2011-03-04 10:55:47 -08001// 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
Nigel Tao6a186d32011-04-20 09:57:05 +10005// Package httptest provides utilities for HTTP testing.
Brad Fitzpatrickda679db2011-03-04 10:55:47 -08006package httptest
7
8import (
Brad Fitzpatrickda679db2011-03-04 10:55:47 -08009 "bytes"
10 "http"
Brad Fitzpatrickda679db2011-03-04 10:55:47 -080011)
12
13// ResponseRecorder is an implementation of http.ResponseWriter that
14// records its mutations for later inspection in tests.
Brad Fitzpatrickda679db2011-03-04 10:55:47 -080015type ResponseRecorder struct {
Brad Fitzpatrickaae7b692011-03-10 08:17:22 -080016 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
Brad Fitzpatrickda679db2011-03-04 10:55:47 -080020}
21
22// NewRecorder returns an initialized ResponseRecorder.
23func NewRecorder() *ResponseRecorder {
24 return &ResponseRecorder{
Brad Fitzpatrick2c420ec2011-03-09 09:41:01 -080025 HeaderMap: make(http.Header),
26 Body: new(bytes.Buffer),
Brad Fitzpatrickda679db2011-03-04 10:55:47 -080027 }
28}
29
30// DefaultRemoteAddr is the default remote address to return in RemoteAddr if
31// an explicit DefaultRemoteAddr isn't set on ResponseRecorder.
32const DefaultRemoteAddr = "1.2.3.4"
33
Brad Fitzpatrick2c420ec2011-03-09 09:41:01 -080034// Header returns the response headers.
35func (rw *ResponseRecorder) Header() http.Header {
36 return rw.HeaderMap
Brad Fitzpatrickda679db2011-03-04 10:55:47 -080037}
38
39// Write always succeeds and writes to rw.Body, if not nil.
Russ Coxc2049d22011-11-01 22:04:37 -040040func (rw *ResponseRecorder) Write(buf []byte) (int, error) {
Brad Fitzpatrickda679db2011-03-04 10:55:47 -080041 if rw.Body != nil {
42 rw.Body.Write(buf)
43 }
Brad Fitzpatrickf1928912011-03-15 10:13:25 -070044 if rw.Code == 0 {
45 rw.Code = http.StatusOK
46 }
Brad Fitzpatrickda679db2011-03-04 10:55:47 -080047 return len(buf), nil
48}
49
50// WriteHeader sets rw.Code.
51func (rw *ResponseRecorder) WriteHeader(code int) {
52 rw.Code = code
53}
54
55// Flush sets rw.Flushed to true.
56func (rw *ResponseRecorder) Flush() {
57 rw.Flushed = true
58}