-
-
Notifications
You must be signed in to change notification settings - Fork 672
/
Copy pathhandler.go
64 lines (56 loc) · 1.54 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
package error
import (
"fmt"
"net/http"
"strings"
"unicode"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
"github.com/gotify/server/v2/model"
)
// Handler creates a gin middleware for handling errors.
func Handler() gin.HandlerFunc {
return func(c *gin.Context) {
c.Next()
if len(c.Errors) > 0 {
for _, e := range c.Errors {
switch e.Type {
case gin.ErrorTypeBind:
errs, ok := e.Err.(validator.ValidationErrors)
if !ok {
writeError(c, e.Error())
return
}
var stringErrors []string
for _, err := range errs {
stringErrors = append(stringErrors, validationErrorToText(err))
}
writeError(c, strings.Join(stringErrors, "; "))
default:
writeError(c, e.Err.Error())
}
}
}
}
}
func validationErrorToText(e validator.FieldError) string {
runes := []rune(e.Field())
runes[0] = unicode.ToLower(runes[0])
fieldName := string(runes)
switch e.Tag() {
case "required":
return fmt.Sprintf("Field '%s' is required", fieldName)
case "max":
return fmt.Sprintf("Field '%s' must be less or equal to %s", fieldName, e.Param())
case "min":
return fmt.Sprintf("Field '%s' must be more or equal to %s", fieldName, e.Param())
}
return fmt.Sprintf("Field '%s' is not valid", fieldName)
}
func writeError(ctx *gin.Context, errString string) {
status := http.StatusBadRequest
if ctx.Writer.Status() != http.StatusOK {
status = ctx.Writer.Status()
}
ctx.JSON(status, &model.Error{Error: http.StatusText(status), ErrorCode: status, ErrorDescription: errString})
}