-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
92 lines (77 loc) · 2.44 KB
/
handler.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
/*
Package helper for handling response to client
*/
package helper
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
)
// Response is response helper to send to client/ user
type Response struct{
Status int `json:"status"`
Method string `json:"method"`
Message string `json:"message"`
Data interface{} `json:"data"`
}
// ErrorResponse is a response that containing error
// Details of the error shoul not be technical as it will be sent to the user
type ErrorResponse struct{
Status int `json:"status"`
Method string `json:"method"`
Error interface{} `json:"error"`
}
// Error is custom dbError struct
type Error struct {
ErrCode uint `json:"code"`
Message string `json:"message,omitempty"`
Error error `json:"error"`
}
// APIResponse will send JSON response to the client and some additional detail
func APIResponse(c *gin.Context, statusCode int, message string, data interface{}) {
// prepare the response before sending to the client
res := Response{
Status : statusCode,
Method : c.Request.Method,
Message : message,
Data : data,
}
// Send wrapped data to client
c.JSON(
statusCode,
res,
)
// In case error occur (starting from code 400 and up)
// it will send an abort opreation with error code as the header
if statusCode >= 400 {
defer c.AbortWithStatus(statusCode)
}
}
// APIErrorResponse will send JSON response with error value to the client
func APIErrorResponse(c *gin.Context, statusCode int, err interface{}) {
// Prepare the data before sending to the client
res := ErrorResponse{
Status : statusCode,
Method : c.Request.Method,
Error : err,
}
// Send wrapped data to client
c.JSON(
statusCode,
res,
)
defer c.AbortWithStatus(statusCode)
}
// ValidationError is a 'Request' error detail generator
// it will break given error value into detailed error message
// so we know which field is the cause of error upon handling request
func ValidationError(err error) (eMessage *[]string) {
// Create list of error message
eMsg := []string{}
for _, e := range err.(validator.ValidationErrors) {
msg := fmt.Sprintf("Field error :'%s', condition: '%s'", e.Field(), e.ActualTag())
eMsg = append(eMsg, msg)
}
eMessage = &eMsg
return
}