2011-03-25 00:46:17 +01:00
|
|
|
// Copyright 2011 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
2011-05-20 02:18:15 +02:00
|
|
|
// Package httptest provides utilities for HTTP testing.
|
2011-03-25 00:46:17 +01:00
|
|
|
package httptest
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"http"
|
|
|
|
)
|
|
|
|
|
|
|
|
// ResponseRecorder is an implementation of http.ResponseWriter that
|
|
|
|
// records its mutations for later inspection in tests.
|
|
|
|
type ResponseRecorder struct {
|
|
|
|
Code int // the HTTP response code from WriteHeader
|
|
|
|
HeaderMap http.Header // the HTTP response headers
|
|
|
|
Body *bytes.Buffer // if non-nil, the bytes.Buffer to append written data to
|
|
|
|
Flushed bool
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewRecorder returns an initialized ResponseRecorder.
|
|
|
|
func NewRecorder() *ResponseRecorder {
|
|
|
|
return &ResponseRecorder{
|
|
|
|
HeaderMap: make(http.Header),
|
|
|
|
Body: new(bytes.Buffer),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// DefaultRemoteAddr is the default remote address to return in RemoteAddr if
|
|
|
|
// an explicit DefaultRemoteAddr isn't set on ResponseRecorder.
|
|
|
|
const DefaultRemoteAddr = "1.2.3.4"
|
|
|
|
|
|
|
|
// Header returns the response headers.
|
|
|
|
func (rw *ResponseRecorder) Header() http.Header {
|
|
|
|
return rw.HeaderMap
|
|
|
|
}
|
|
|
|
|
|
|
|
// Write always succeeds and writes to rw.Body, if not nil.
|
2011-12-03 03:17:34 +01:00
|
|
|
func (rw *ResponseRecorder) Write(buf []byte) (int, error) {
|
2011-03-25 00:46:17 +01:00
|
|
|
if rw.Body != nil {
|
|
|
|
rw.Body.Write(buf)
|
|
|
|
}
|
|
|
|
if rw.Code == 0 {
|
|
|
|
rw.Code = http.StatusOK
|
|
|
|
}
|
|
|
|
return len(buf), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// WriteHeader sets rw.Code.
|
|
|
|
func (rw *ResponseRecorder) WriteHeader(code int) {
|
|
|
|
rw.Code = code
|
|
|
|
}
|
|
|
|
|
|
|
|
// Flush sets rw.Flushed to true.
|
|
|
|
func (rw *ResponseRecorder) Flush() {
|
|
|
|
rw.Flushed = true
|
|
|
|
}
|