-
Notifications
You must be signed in to change notification settings - Fork 0
/
response_writer.go
40 lines (32 loc) · 921 Bytes
/
response_writer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package httptest
import (
"encoding/json"
"fmt"
"net/http"
)
// ResponseWriter is a struct that handles the response writing.
type ResponseWriter struct {
w http.ResponseWriter
}
// SetBodyBytes sets the response body.
func (r *ResponseWriter) SetBodyBytes(b []byte) (int, error) {
return r.w.Write(b)
}
// SetBodyJSON marshals s to JSON and sets it as the response body, and
// sets the Content-Type header to application/json.
func (r *ResponseWriter) SetBodyJSON(s any) (int, error) {
r.w.Header().Set("Content-Type", "application/json")
b, err := json.Marshal(&s)
if err != nil {
return 0, fmt.Errorf("json.Marshal: %w", err)
}
return r.w.Write(b)
}
// SetStatusCode sets the response status code.
func (r *ResponseWriter) SetStatusCode(statusCode int) {
r.w.WriteHeader(statusCode)
}
// Header returns the response headers.
func (r *ResponseWriter) Header() http.Header {
return r.w.Header()
}