-
Notifications
You must be signed in to change notification settings - Fork 0
/
respond.go
31 lines (27 loc) · 1.05 KB
/
respond.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
package jsonapi
import (
"net/http"
)
// Respond encodes v in to a JSON:API object and writes it to the body of response w. It also sets
// statusCode as the response status code.
func Respond(w http.ResponseWriter, r *http.Request, statusCode int, v interface{}, p *MarshalParams) error {
body, err := Marshal(v, p)
if err != nil {
return err
}
return respond(w, r, statusCode, body)
}
// RespondError encodes v in to a JSON:API error object and writes it to the body of response w. It
// also sets statusCode as the response status code.
func RespondError(w http.ResponseWriter, r *http.Request, statusCode int, p *MarshalParams, errs ...Error) error {
// TODO figure out how to trigger this error for test coverage
body, _ := MarshalErrors(p, errs...)
return respond(w, r, statusCode, body)
}
func respond(w http.ResponseWriter, r *http.Request, statusCode int, body []byte) (err error) {
w.Header().Set("Content-Type", ContentType)
w.WriteHeader(statusCode)
// TODO figure out how to trigger this error for test coverage
_, err = w.Write(body)
return err
}