-
Notifications
You must be signed in to change notification settings - Fork 0
/
response-utils.go
100 lines (83 loc) · 2.29 KB
/
response-utils.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package celeritas
import (
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"net/http"
"path"
"path/filepath"
)
func (c *Celeritas) ReadJSON(w http.ResponseWriter, r *http.Request, data interface{}) error {
maxBytes := 1048576 // one megabyte
r.Body = http.MaxBytesReader(w, r.Body, int64(maxBytes))
dec := json.NewDecoder(r.Body)
err := dec.Decode(data)
if err != nil {
return err
}
err = dec.Decode(&struct{}{})
if err != io.EOF {
return errors.New("body must only have a single json value")
}
return nil
}
func (c *Celeritas) WriteJson(w http.ResponseWriter, status int, data interface{}, headers ...http.Header) error {
out, err := json.MarshalIndent(data, "", "\t")
if err != nil {
return err
}
if len(headers) > 0 {
for key, value := range headers[0] {
w.Header()[key] = value
}
}
w.Header().Set("Content_Type", "application/json")
w.WriteHeader(status)
_, err = w.Write(out)
if err != nil {
return err
}
return nil
}
func (c *Celeritas) WriteXML(w http.ResponseWriter, status int, data interface{}, headers ...http.Header) error {
out, err := xml.MarshalIndent(data, "", " ")
if err != nil {
return err
}
if len(headers) > 0 {
for key, value := range headers[0] {
w.Header()[key] = value
}
}
w.Header().Set("Content-Type", "application/xml")
w.WriteHeader(status)
_, err = w.Write(out)
if err != nil {
return err
}
return nil
}
func (c *Celeritas) DownloadFile(w http.ResponseWriter, r *http.Request, pathToFile, fileName string) error {
fp := path.Join(pathToFile, fileName)
fileToServe := filepath.Clean(fp)
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; file=\"%s\"", fileName))
http.ServeFile(w, r, fileToServe)
return nil
}
func (c *Celeritas) Error404(w http.ResponseWriter, r *http.Request) {
c.ErrorStatus(w, http.StatusNotFound)
}
func (c *Celeritas) Error500(w http.ResponseWriter, r *http.Request) {
c.ErrorStatus(w, http.StatusInternalServerError)
}
func (c *Celeritas) ErrorUnauthorized(w http.ResponseWriter, r *http.Request) {
c.ErrorStatus(w, http.StatusUnauthorized)
}
func (c *Celeritas) ErrorForbidden(w http.ResponseWriter, r *http.Request) {
c.ErrorStatus(w, http.StatusForbidden)
}
func (c *Celeritas) ErrorStatus(w http.ResponseWriter, status int) {
http.Error(w, http.StatusText(status), status)
}