Make HTTPResponseRecorder more useful

This commit is contained in:
Sasha Koshka 2024-12-07 00:53:39 -05:00
parent af6c705d8c
commit c85bd09ac5

27
http.go
View File

@ -11,6 +11,7 @@ type HTTPData struct {
Res struct { Res struct {
Header http.Header Header http.Header
WriteHeader func (statusCode int) WriteHeader func (statusCode int)
Reset func ()
} }
// Req is the HTTP request. // Req is the HTTP request.
Req *http.Request Req *http.Request
@ -21,20 +22,16 @@ var _ http.ResponseWriter = new(HTTPResponseRecorder)
// HTTPResponseRecorder is an http.ResponseWriter that can buffer a response to // HTTPResponseRecorder is an http.ResponseWriter that can buffer a response to
// be played back later. // be played back later.
type HTTPResponseRecorder struct { type HTTPResponseRecorder struct {
statusCode int Status int
header http.Header Head http.Header
buffer bytes.Buffer buffer bytes.Buffer
} }
func (this *HTTPResponseRecorder) Header () http.Header { func (this *HTTPResponseRecorder) Header () http.Header {
if this.header == nil { if this.Head == nil {
this.header = make(http.Header) this.Head = make(http.Header)
} }
return this.header return this.Head
}
func (this *HTTPResponseRecorder) SetHeader (header http.Header) {
this.header = header
} }
func (this *HTTPResponseRecorder) Write (buffer []byte) (int, error) { func (this *HTTPResponseRecorder) Write (buffer []byte) (int, error) {
@ -42,13 +39,17 @@ func (this *HTTPResponseRecorder) Write (buffer []byte) (int, error) {
} }
func (this *HTTPResponseRecorder) WriteHeader (statusCode int) { func (this *HTTPResponseRecorder) WriteHeader (statusCode int) {
this.statusCode = statusCode this.Status = statusCode
} }
// Play replays the response to the given http.ResponseWriter. This resets the // Play replays the response to the given http.ResponseWriter. This resets the
// recorder. // recorder.
func (this *HTTPResponseRecorder) Play (res http.ResponseWriter) error { func (this *HTTPResponseRecorder) Play (res http.ResponseWriter) error {
defer this.Reset() defer this.Reset()
header := res.Header()
for name, value := range this.Head {
header[name] = value
}
res.WriteHeader(this.Status)
_, err := io.Copy(res, &this.buffer) _, err := io.Copy(res, &this.buffer)
return err return err
} }
@ -56,6 +57,6 @@ func (this *HTTPResponseRecorder) Play (res http.ResponseWriter) error {
// Reset resets this response recorder so it can be used again. // Reset resets this response recorder so it can be used again.
func (this *HTTPResponseRecorder) Reset () { func (this *HTTPResponseRecorder) Reset () {
this.buffer.Reset() this.buffer.Reset()
this.header = nil this.Head = nil
this.statusCode = http.StatusOK this.Status = http.StatusOK
} }