-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
96 lines (82 loc) · 2.31 KB
/
http.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
// Copyright (c) 2018 The VeChainThor developers
// Copyright (c) 2019 The PlayMaker developers
// Distributed under the GNU Lesser General Public License v3.0 software license, see the accompanying
// file LICENSE or <https://www.gnu.org/licenses/lgpl-3.0.html>
package utils
import (
"encoding/json"
"io"
"net/http"
)
type httpError struct {
cause error
status int
}
func (e *httpError) Error() string {
return e.cause.Error()
}
// HTTPError create an error with http status code.
func HTTPError(cause error, status int) error {
return &httpError{
cause: cause,
status: status,
}
}
// BadRequest convenience method to create http bad request error.
func BadRequest(cause error) error {
return &httpError{
cause: cause,
status: http.StatusBadRequest,
}
}
// Forbidden convenience method to create http forbidden error.
func Forbidden(cause error) error {
return &httpError{
cause: cause,
status: http.StatusForbidden,
}
}
// HandlerFunc like http.HandlerFunc, bu it returns an error.
// If the returned error is httpError type, httpError.status will be responded,
// otherwise http.StatusInternalServerError responded.
type HandlerFunc func(http.ResponseWriter, *http.Request) error
// WrapHandlerFunc convert HandlerFunc to http.HandlerFunc.
func WrapHandlerFunc(f HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
err := f(w, r)
if err != nil {
if he, ok := err.(*httpError); ok {
if he.cause != nil {
http.Error(w, he.cause.Error(), he.status)
} else {
w.WriteHeader(he.status)
}
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
}
}
// content types
const (
JSONContentType = "application/json; charset=utf-8"
OctetStreamContentType = "application/octet-stream"
)
// ParseJSON parse a JSON object using strict mode.
func ParseJSON(r io.Reader, v interface{}) error {
decoder := json.NewDecoder(r)
decoder.DisallowUnknownFields()
return decoder.Decode(v)
}
// WriteJSON reponse a object in JSON enconding.
func WriteJSON(w http.ResponseWriter, obj interface{}) error {
data, err := json.Marshal(obj)
if err != nil {
return HTTPError(err, 500)
}
w.Header().Set("Content-Type", JSONContentType)
w.Write(data)
return nil
}
// M shortcut for type map[string]interface{}.
type M map[string]interface{}