-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.go
73 lines (60 loc) · 1.33 KB
/
common.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
package pantsu
import (
"encoding/json"
"github.com/valyala/fasthttp"
)
var methodList = []string{
fasthttp.MethodGet,
fasthttp.MethodPost,
fasthttp.MethodPut,
fasthttp.MethodDelete,
fasthttp.MethodPatch,
}
func WithMiddlewares(middleware ...MiddlewareFunc) MiddlewareFunc {
return func(next Handler) Handler {
h := next
if len(middleware) <= 0 {
return h
}
for i := len(middleware) - 1; i >= 0; i-- {
if middleware[i] == nil {
continue
}
h = middleware[i](h)
}
return h
}
}
func String(ctx *fasthttp.RequestCtx, str string) (err error) {
_, err = ctx.WriteString(str)
return
}
func Error(ctx *fasthttp.RequestCtx, status int, msg string) error {
ctx.SetStatusCode(status)
ctx.WriteString(msg)
return nil
}
func NotFound(ctx *fasthttp.RequestCtx) error {
ctx.Response.Reset()
return JSON(ctx, 404, map[string]interface{}{
`statusCode`: 404,
`error`: `not found`,
})
}
func Corrupt(ctx *fasthttp.RequestCtx) error {
ctx.Response.Reset()
return JSON(ctx, 500, map[string]interface{}{
`statusCode`: 500,
`error`: `internal server error`,
})
}
func JSON(ctx *fasthttp.RequestCtx, statusCode int, v interface{}) (err error) {
ctx.SetContentType(`application/json`)
ctx.SetStatusCode(statusCode)
byt, err := json.Marshal(v)
if err != nil {
return
}
_, err = ctx.Write(byt)
return
}