blob: 22827a31db1b42f8f5cbdacc07dc77fc4cf9623c [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
5// The httptest package provides utilities for HTTP testing.
6package httptest
7
8import (
Brad Fitzpatrickda679db2011-03-04 10:55:47 -08009 "bytes"
10 "http"
Brad Fitzpatrickda679db2011-03-04 10:55:47 -080011 "os"
12)
13
14// ResponseRecorder is an implementation of http.ResponseWriter that
15// records its mutations for later inspection in tests.
Brad Fitzpatrickda679db2011-03-04 10:55:47 -080016type ResponseRecorder struct {
Brad Fitzpatrick2c420ec2011-03-09 09:41:01 -080017 Code int // the HTTP response code from WriteHeader
18 HeaderMap http.Header // the HTTP response headers
19 Body *bytes.Buffer // if non-nil, the bytes.Buffer to append written data to
20 Flushed bool
Brad Fitzpatrickda679db2011-03-04 10:55:47 -080021 FakeRemoteAddr string // the fake RemoteAddr to return, or "" for DefaultRemoteAddr
22 FakeUsingTLS bool // whether to return true from the UsingTLS method
23}
24
25// NewRecorder returns an initialized ResponseRecorder.
26func NewRecorder() *ResponseRecorder {
27 return &ResponseRecorder{
Brad Fitzpatrick2c420ec2011-03-09 09:41:01 -080028 HeaderMap: make(http.Header),
29 Body: new(bytes.Buffer),
Brad Fitzpatrickda679db2011-03-04 10:55:47 -080030 }
31}
32
33// DefaultRemoteAddr is the default remote address to return in RemoteAddr if
34// an explicit DefaultRemoteAddr isn't set on ResponseRecorder.
35const DefaultRemoteAddr = "1.2.3.4"
36
37// RemoteAddr returns the value of rw.FakeRemoteAddr, if set, else
38// returns DefaultRemoteAddr.
39func (rw *ResponseRecorder) RemoteAddr() string {
40 if rw.FakeRemoteAddr != "" {
41 return rw.FakeRemoteAddr
42 }
43 return DefaultRemoteAddr
44}
45
46// UsingTLS returns the fake value in rw.FakeUsingTLS
47func (rw *ResponseRecorder) UsingTLS() bool {
48 return rw.FakeUsingTLS
49}
50
Brad Fitzpatrick2c420ec2011-03-09 09:41:01 -080051// Header returns the response headers.
52func (rw *ResponseRecorder) Header() http.Header {
53 return rw.HeaderMap
Brad Fitzpatrickda679db2011-03-04 10:55:47 -080054}
55
56// Write always succeeds and writes to rw.Body, if not nil.
57func (rw *ResponseRecorder) Write(buf []byte) (int, os.Error) {
58 if rw.Body != nil {
59 rw.Body.Write(buf)
60 }
61 return len(buf), nil
62}
63
64// WriteHeader sets rw.Code.
65func (rw *ResponseRecorder) WriteHeader(code int) {
66 rw.Code = code
67}
68
69// Flush sets rw.Flushed to true.
70func (rw *ResponseRecorder) Flush() {
71 rw.Flushed = true
72}