-
Notifications
You must be signed in to change notification settings - Fork 4
/
context.go
81 lines (61 loc) · 1.48 KB
/
context.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
package router
import (
"net/http"
"github.com/gin-gonic/gin"
)
type Context struct {
*gin.Context
}
func (c *Context) AbortWithError(statusCode int, err Error) {
c.Header("Content-Type", "application/json")
_ = c.Context.AbortWithError(statusCode, err)
}
// 200
func (c *Context) JSON(data interface{}) {
c.Context.JSON(http.StatusOK, data)
}
func (c *Context) Created() {
c.Context.Status(http.StatusCreated)
}
func (c *Context) OK() {
c.Context.Status(http.StatusNoContent)
}
// 300
func (c *Context) NotModified() {
c.Context.Status(http.StatusNotModified)
}
// 400
func (c *Context) BadRequest(err Error) {
c.AbortWithError(http.StatusBadRequest, err)
}
func (c *Context) Unauthorized(err Error) {
c.AbortWithError(http.StatusUnauthorized, err)
}
func (c *Context) NotFound(err Error) {
c.AbortWithError(http.StatusNotFound, err)
}
func (c *Context) Conflict(err Error) {
c.AbortWithError(http.StatusConflict, err)
}
func (c *Context) Unprocessable(err Error) {
c.AbortWithError(http.StatusUnprocessableEntity, err)
}
// 500
func (c *Context) Abort(err Error) {
c.AbortWithError(http.StatusInternalServerError, err)
}
func (c *Context) AbortWithCode(code int, err Error) {
c.AbortWithError(code, err)
}
func (c *Context) ParseBody(obj interface{}) error {
err := c.BindJSON(obj)
if err != nil {
c.BadRequest(Error{
Code: ErrFailedToParseBody,
PublicMessage: "Failed to parse the request.",
PrivateMessage: err.Error(),
})
return err
}
return nil
}