-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.go
60 lines (53 loc) · 1.84 KB
/
response.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package chio
import (
"encoding/json"
"encoding/xml"
"fmt"
"io"
"net/http"
)
// Empty writes the status code and sets the Content-Length header to 0
func Empty(w http.ResponseWriter, code int) {
w.WriteHeader(code)
w.Header().Set(`Content-Length`, `0`)
}
// WriteString writes s to the body and sets the Content-Type to text/plain
func WriteString(w http.ResponseWriter, code int, s string) {
w.WriteHeader(code)
w.Header().Set(`Content-Type`, `text/plain`)
if _, err := w.Write([]byte(s)); err != nil {
panic(err)
}
}
// WriteJSON writes v to the body as WriteJSON and sets the Content-Type to application/json. If marshalling fails, it panics.
func WriteJSON(w http.ResponseWriter, code int, v any) {
w.WriteHeader(code)
w.Header().Set(`Content-Type`, `application/json`)
if err := json.NewEncoder(w).Encode(v); err != nil {
panic(fmt.Errorf(`error encoding JSON into response: %w`, err))
}
}
// WriteXML writes v to the body as WriteXML and sets the Content-Type to application/xml. If marshalling fails, it panics.
func WriteXML(w http.ResponseWriter, code int, v any) {
w.WriteHeader(code)
w.Header().Set(`Content-Type`, `application/xml`)
if err := xml.NewEncoder(w).Encode(v); err != nil {
panic(fmt.Errorf(`error encoding XML into response: %w`, err))
}
}
// StreamBlob copies data from r to w
func StreamBlob(w http.ResponseWriter, code int, contentType string, r io.Reader) {
w.WriteHeader(code)
w.Header().Set(`Content-Type`, contentType)
if _, err := io.Copy(w, r); err != nil {
panic(fmt.Errorf(`error streaming blob into response: %w`, err))
}
}
// WriteBlob writes v to the body
func WriteBlob(w http.ResponseWriter, code int, contentType string, v []byte) {
w.WriteHeader(code)
w.Header().Set(`Content-Type`, contentType)
if _, err := w.Write(v); err != nil {
panic(fmt.Errorf(`error writing blob into response: %w`, err))
}
}