-
Notifications
You must be signed in to change notification settings - Fork 0
/
requestutils.go
71 lines (55 loc) · 1.73 KB
/
requestutils.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
package utils
import (
"encoding/json"
http "github.com/valyala/fasthttp"
)
type errorResp map[string]string
var (
strContentType = []byte("Content-Type")
strApplicationJSON = []byte("application/json")
)
// WriteJSON ...
func WriteJSON(ctx *http.RequestCtx, obj interface{}) {
ctx.Response.Header.SetCanonical(strContentType, strApplicationJSON)
if err := json.NewEncoder(ctx).Encode(obj); err != nil {
WriteError(ctx, http.StatusInternalServerError, newRespError(err.Error()))
}
}
// SetStatus ...
func SetStatus(ctx *http.RequestCtx, code int) {
ctx.Response.SetStatusCode(code)
}
// WriteError ...
func WriteError(ctx *http.RequestCtx, code int, obj interface{}) {
ctx.Response.SetStatusCode(code)
if err := json.NewEncoder(ctx).Encode(obj); err != nil {
LogError(err.Error())
panic(err)
}
}
// RenderNotFoundError ...
func RenderNotFoundError(ctx *http.RequestCtx, msg string) {
WriteError(ctx, http.StatusNotFound, newRespError(msg))
}
// RenderUnauthorized ...
func RenderUnauthorized(ctx *http.RequestCtx, msg string) {
WriteError(ctx, http.StatusUnauthorized, newRespError(msg))
}
// RenderInternalError ...
func RenderInternalError(ctx *http.RequestCtx, msg string) {
WriteError(ctx, http.StatusInternalServerError, newRespError(msg))
}
func newRespError(msg string) errorResp {
return errorResp{"error": msg}
}
// RenderValidationErrors ...
func RenderValidationErrors(ctx *http.RequestCtx, verrors map[string][]string) {
verrorsJSON, err := json.MarshalIndent(verrors, "", " ")
LogInfo("Validation errors:\n", string(verrorsJSON))
if err != nil {
LogError("Unable to marshal validation errors: ", err)
RenderInternalError(ctx, err.Error())
return
}
WriteError(ctx, http.StatusUnprocessableEntity, verrors)
}