-
Notifications
You must be signed in to change notification settings - Fork 0
/
gin.go
104 lines (92 loc) · 2.05 KB
/
gin.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
92
93
94
95
96
97
98
99
100
101
102
103
104
package main
import (
"fmt"
"log"
"github.com/gin-gonic/gin"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
func prometheusHandler() gin.HandlerFunc {
h := promhttp.Handler()
return func(c *gin.Context) {
h.ServeHTTP(c.Writer, c.Request)
}
}
func (d *Ingest) registerBasicChecks() {
// Sanity GET request
d.Engine.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
// / so things know we exist
d.Engine.GET("/", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "ingestd",
})
})
// metrics
d.Engine.GET("/metrics", prometheusHandler())
}
func (d *Ingest) registerNoRouteCheck() {
d.Engine.NoRoute(func(c *gin.Context) {
// Handle internal errors by sending the error to the client
defer func() {
if err := recover(); err != nil {
log.Println("Caught 500:", err)
c.AbortWithStatusJSON(500, gin.H{
"message": fmt.Sprint(err),
})
}
}()
// Get the json payload
data := make(map[string]interface{})
err := c.BindJSON(&data)
if err != nil {
log.Println("Error parsing JSON")
log.Println(err)
c.AbortWithStatusJSON(400, gin.H{
"message": fmt.Sprint(err),
})
return
}
// Get the route
schema, table := d.parsePath(c.Request.URL.Path)
if schema == "" || table == "" {
log.Println("No route found")
c.AbortWithStatusJSON(404, gin.H{
"message": "No route found",
})
return
}
if d.canInsert(data) {
switch d.getDBType() {
case "mysql", "postgres":
err = d.Insert(schema, table, data)
if err != nil {
d.abort(c, err)
return
}
case "redis":
err = d.Publish(d.makeChannelName(schema, table), data)
if err != nil {
d.abort(c, err)
return
}
}
c.JSON(200, gin.H{
"message": "Success",
})
} else {
c.AbortWithStatusJSON(401, gin.H{
"message": "Not Authorized",
})
}
})
}
func (d *Ingest) abort(c *gin.Context, err error) {
log.Println("Error inserting data to", d.getDBType())
log.Println(err)
c.AbortWithStatusJSON(500, gin.H{
"message": fmt.Sprint(err),
})
}