forked from ant0ine/go-json-rest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.go
83 lines (72 loc) · 2.09 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package rest
import (
"compress/gzip"
"encoding/json"
"net/http"
)
// Inherit from an object implementing the http.ResponseWriter interface,
// and provide additional methods.
type Response struct {
http.ResponseWriter
isGzipped bool
isIndented bool
statusCode int
wroteHeader bool
}
// Overloading of the http.ResponseWriter method.
// Just record the status code for logging.
func (self *Response) WriteHeader(code int) {
self.ResponseWriter.WriteHeader(code)
self.statusCode = code
self.wroteHeader = true
}
// Overloading of the http.ResponseWriter method.
// Provide additional capabilities, like transparent gzip encoding.
func (self *Response) Write(b []byte) (int, error) {
if self.isGzipped {
self.Header().Set("Content-Encoding", "gzip")
}
if !self.wroteHeader {
self.WriteHeader(http.StatusOK)
}
if self.isGzipped {
gzipWriter := gzip.NewWriter(self.ResponseWriter)
defer gzipWriter.Close()
return gzipWriter.Write(b)
}
return self.ResponseWriter.Write(b)
}
// Encode the object in JSON, set the content-type header,
// and call Write.
func (self *Response) WriteJson(v interface{}) error {
self.Header().Set("content-type", "application/json; charset=utf-8")
var b []byte
var err error
if self.isIndented {
b, err = json.MarshalIndent(v, "", " ")
} else {
b, err = json.Marshal(v)
}
if err != nil {
return err
}
self.Write(b)
return nil
}
// Produce an error response in JSON with the following structure, '{"Error":"My error message"}'
// The standard plain text net/http Error helper can still be called like this:
// http.Error(w, "error message", code)
func Error(w *Response, error string, code int) {
w.Header().Set("content-type", "application/json")
w.WriteHeader(code)
err := w.WriteJson(map[string]string{"Error": error})
if err != nil {
panic(err)
}
}
// Produce a 404 response with the following JSON, '{"Error":"Resource not found"}'
// The standard plain text net/http NotFound helper can still be called like this:
// http.NotFound(w, r.Request)
func NotFound(w *Response, r *Request) {
Error(w, "Resource not found", http.StatusNotFound)
}