This repository has been archived by the owner on Jun 30, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.go
75 lines (66 loc) · 1.99 KB
/
utils.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 main
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
"gopkg.in/go-playground/validator.v9"
"io/ioutil"
)
type APIError struct {
Code string `json:"code,omitempty"`
Title string `json:"title,omitempty"`
Detail string `json:"detail,omitempty"`
Source string `json:"source,omitempty"`
}
var SQLError = APIError{Code: "database_error", Title: "Unknown database exception"}
type stackTracer interface {
StackTrace() errors.StackTrace
}
func (q *NgWebAPI) apiException(c *gin.Context, status int, err error, errors ...APIError) {
logCtx := q.log.New("err", err)
if err, ok := err.(stackTracer); ok {
frame := err.StackTrace()[0]
logCtx = logCtx.New("origin", fmt.Sprintf("%v [%n]", frame, frame))
}
res, _ := ioutil.ReadAll(c.Request.Body)
logCtx.New("uri", c.Request.RequestURI, "body", res).Warn("Error in handler")
q.apiError(c, status, errors...)
}
func (q *NgWebAPI) apiError(c *gin.Context, status int, errors ...APIError) {
c.JSON(status, gin.H{"errors": errors})
}
type res map[string]interface{}
func (q *NgWebAPI) apiSuccess(c *gin.Context, status int, data interface{}) {
c.JSON(status, gin.H{"data": data})
}
func (q *NgWebAPI) BindValid(c *gin.Context, output interface{}) bool {
var err error
err = c.BindJSON(&output)
if err != nil {
q.apiError(c, 400, APIError{
Code: "invalid_format",
Title: "JSON payload format doesn't match expectation"})
return false
}
err = validate.Struct(output)
if err != nil {
if vde, ok := err.(validator.ValidationErrors); ok {
var errors []APIError
for _, fe := range vde {
errors = append(errors, APIError{
Code: "invalid_field",
Source: fe.Field(),
Title: fmt.Sprintf("Validator '%s' failed on attribute '%s'", fe.Tag(), fe.Field()),
})
}
c.JSON(400, gin.H{"errors": errors})
return false
}
q.apiException(c, 500, errors.WithStack(err), APIError{
Code: "unk_validation",
Title: "An unexpected validation error has occurred",
})
return false
}
return true
}