-
Notifications
You must be signed in to change notification settings - Fork 13
/
response.go
75 lines (53 loc) · 1.38 KB
/
response.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
package response
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/coretrix/hitrix/pkg/errors"
)
const ResponseBody = "response_body"
type Error struct {
GlobalError string `json:"GlobalError,omitempty"`
FieldsError map[string]string `json:"FieldsError,omitempty"`
Result *interface{} `json:"Result,omitempty"`
}
func SuccessResponse(c *gin.Context, data interface{}) {
c.Set(ResponseBody, data)
if data != nil {
c.JSON(http.StatusOK, data)
return
}
c.JSON(http.StatusOK, gin.H{})
}
func NotFoundResponse(c *gin.Context) {
c.JSON(http.StatusNotFound, gin.H{})
}
func ErrorResponseGlobal(c *gin.Context, globalError interface{}, data interface{}) {
result := &Error{}
if data != nil {
result.Result = &data
}
err, ok := globalError.(*errors.PermissionError)
if ok {
c.Set(ResponseBody, err.Error())
c.AbortWithStatusJSON(http.StatusForbidden, err.Error())
return
}
err1, ok1 := globalError.(error)
if ok1 {
result.GlobalError = err1.Error()
} else {
result.GlobalError = globalError.(string)
}
c.Set(ResponseBody, result)
c.JSON(http.StatusBadRequest, result)
}
func ErrorResponseFields(c *gin.Context, fieldsError errors.FieldErrors, data interface{}) {
result := &Error{
FieldsError: fieldsError,
}
if data != nil {
result.Result = &data
}
c.Set(ResponseBody, result)
c.JSON(http.StatusBadRequest, result)
}