-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
60 lines (50 loc) · 1.53 KB
/
json.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 jeen
import (
"encoding/json"
"net/http"
)
type Json struct {
// response writer
writer http.ResponseWriter
}
// create new json response
func newJson(rw http.ResponseWriter) *Json {
return &Json{
writer: rw,
}
}
// Success is shortcut for Response with StatusOK = 200,
func (j *Json) Success(data interface{}) error {
return j.Response(http.StatusOK, data)
}
// Error is shortcut for Response with StatusInternalServerError = 500,
func (j *Json) Error(data interface{}) error {
return j.Response(http.StatusInternalServerError, data)
}
// Timeout is shortcut for Response with StatusGatewayTimeout = 504,
func (j *Json) Timeout(data interface{}) error {
return j.Response(http.StatusGatewayTimeout, data)
}
// Forbidden is shortcut for Response with StatusForbidden = 403,
func (j *Json) Forbidden(data interface{}) error {
return j.Response(http.StatusForbidden, data)
}
// NotFound is shortcut for Response with StatusNotFound = 404,
func (j *Json) NotFound(data interface{}) error {
return j.Response(http.StatusNotFound, data)
}
// Unauthorized is shortcut for Response with StatusUnauthorized = 401,
func (j *Json) Unauthorized(data interface{}) error {
return j.Response(http.StatusUnauthorized, data)
}
// Response response json output to browser,
func (j *Json) Response(statusCode int, data interface{}) error {
out, err := json.Marshal(data)
if err != nil {
return err
}
j.writer.Header().Set("Content-Type", "application/json; charset=utf-8")
j.writer.WriteHeader(statusCode)
_, err = j.writer.Write(out)
return err
}