-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmain.go
93 lines (78 loc) · 1.71 KB
/
main.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
package main
import (
"database/sql"
"fmt"
"net/http"
"time"
"github.com/BurtonR/sqlrest/database"
"github.com/BurtonR/sqlrest/handlers"
"github.com/BurtonR/sqlrest/middleware"
_ "github.com/denisenkom/go-mssqldb"
"github.com/gin-gonic/gin"
)
func setupRouter() *gin.Engine {
r := gin.Default()
r.Use(middleware.HmacAuthentication)
// Health check
r.GET("/ping", func(c *gin.Context) {
c.String(200, "pong")
})
r.GET("/connect", func(c *gin.Context) {
connected, err := database.GetConnection()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"message": "failed to connect"})
return
}
if connected {
c.JSON(http.StatusOK, gin.H{"message": "connected"})
}
})
v1 := r.Group("v1")
{
v1.POST("/query", handlers.ExecuteQuery)
v1.POST("/update", handlers.ExecuteUpdate)
v1.PUT("/insert", handlers.ExecuteInsert)
v1.DELETE("/delete", handlers.ExecuteDelete)
v1.POST("/procedure", handlers.ExecuteProcedure)
}
return r
}
func main() {
connectToDb()
ticker := time.NewTicker(2 * time.Minute)
quit := make(chan struct{})
go pinger(ticker, quit)
r := setupRouter()
r.Run(":5050")
}
func pinger(ticker *time.Ticker, quit chan struct{}) {
for {
select {
case <-ticker.C:
connectToDb()
case <-quit:
ticker.Stop()
return
}
}
}
func connectToDb() {
maxRetries := 2
var conn *sql.DB
for i := 0; i < maxRetries; i++ {
connected, err := database.GetConnection()
if err != nil {
fmt.Printf("Unable to connect. Attempt %d of %d", i+1, maxRetries)
fmt.Println()
}
if connected {
return
}
time.Sleep(500 * time.Millisecond)
}
if conn == nil {
fmt.Printf("No database connection after %d attempts", maxRetries)
fmt.Println()
}
return
}