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
92
93
94
95
96
97
98
99
100
101
102
103
|
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func ApplicationRoutes(engine *gin.Engine, rulesManager RulesManager) {
// engine.Static("/", "./frontend/build")
api := engine.Group("/api")
{
api.GET("/rules", func(c *gin.Context) {
success(c, rulesManager.GetRules())
})
api.POST("/rules", func(c *gin.Context) {
var rule Rule
if err := c.ShouldBindJSON(&rule); err != nil {
badRequest(c, err)
return
}
if id, err := rulesManager.AddRule(c, rule); err != nil {
unprocessableEntity(c, err)
} else {
success(c, UnorderedDocument{"id": id})
}
})
api.GET("/rules/:id", func(c *gin.Context) {
hex := c.Param("id")
id, err := RowIDFromHex(hex)
if err != nil {
badRequest(c, err)
return
}
rule, found := rulesManager.GetRule(id)
if !found {
notFound(c, UnorderedDocument{"id": id})
} else {
success(c, rule)
}
})
api.PUT("/rules/:id", func(c *gin.Context) {
hex := c.Param("id")
id, err := RowIDFromHex(hex)
if err != nil {
badRequest(c, err)
return
}
var rule Rule
if err := c.ShouldBindJSON(&rule); err != nil {
badRequest(c, err)
return
}
updated, err := rulesManager.UpdateRule(c, id, rule)
if err != nil {
badRequest(c, err)
} else if !updated {
notFound(c, UnorderedDocument{"id": id})
} else {
success(c, rule)
}
})
}
}
func success(c *gin.Context, obj interface{}) {
c.JSON(http.StatusOK, obj)
}
func badRequest(c *gin.Context, err error) {
c.JSON(http.StatusBadRequest, UnorderedDocument{"result": "error", "error": err.Error()})
//validationErrors, ok := err.(validator.ValidationErrors)
//if !ok {
// log.WithError(err).WithField("rule", rule).Error("oops")
// c.JSON(http.StatusBadRequest, gin.H{})
// return
//}
//
//for _, fieldErr := range validationErrors {
// log.Println(fieldErr)
// c.JSON(http.StatusBadRequest, gin.H{
// "error": fmt.Sprintf("field '%v' does not respect the %v(%v) rule",
// fieldErr.Field(), fieldErr.Tag(), fieldErr.Param()),
// })
// log.WithError(err).WithField("rule", rule).Error("oops")
// return // exit on first error
//}
}
func unprocessableEntity(c *gin.Context, err error) {
c.JSON(http.StatusUnprocessableEntity, UnorderedDocument{"result": "error", "error": err.Error()})
}
func notFound(c *gin.Context, obj interface{}) {
c.JSON(http.StatusNotFound, obj)
}
|