/
database.controller.go
90 lines (72 loc) · 2.41 KB
/
database.controller.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
package controllers
import (
"crypto/tls"
"database/sql"
"fmt"
"log"
"time"
"github.com/Data-Alchemist-ODS/ods-api/models/request"
"github.com/go-sql-driver/mysql"
"github.com/gofiber/fiber/v2"
"github.com/patrickmn/go-cache"
)
// DatabaseController is a contract what this controller can do
type DatabaseController interface {
ConnectToTiDB(c *fiber.Ctx) error
}
// databaseController is a struct that represent the DatabaseController contract
type databaseController struct{}
// NewDatabaseController is the constructor
func NewDatabaseController() DatabaseController {
return &databaseController{}
}
/*
* Implement functions goes down here
*/
func (controller *databaseController) ConnectToTiDB(c *fiber.Ctx) error {
var request request.TiDBConnectionRequest
if err := c.BodyParser(&request); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"message": "failed to parse json",
"status": fiber.StatusBadRequest,
"error": err.Error(),
})
}
mysql.RegisterTLSConfig("tidb", &tls.Config{
MinVersion: tls.VersionTLS12,
// ServerName: "gateway01.eu-central-1.prod.aws.tidbcloud.com",
ServerName: request.ServerName,
})
dataSourceName := fmt.Sprintf("%s:%s@tcp(%s:4000)/%s?tls=tidb", request.User, request.Password, request.ServerName, request.Database)
// db, err := sql.Open("mysql", "4MXeBRmXXzc7uqt.root:<your_password>@tcp(gateway01.eu-central-1.prod.aws.tidbcloud.com:4000)/test?tls=tidb")
db, err := sql.Open("mysql", dataSourceName)
if err != nil {
log.Fatal("failed to connect database", err)
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"message": "failed to connect to TiDB",
"error": err.Error(),
})
}
defer db.Close()
ca := cache.New(5*time.Minute, 10*time.Minute)
// Set the value of the key "foo" to "bar", with the default expiration time
ca.Set("tidb_connection", dataSourceName, cache.NoExpiration)
connection, found := ca.Get("tidb_connection")
if !found {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"message": "failed to connect to TiDB",
"error": err.Error(),
})
}
// var dbName string
// err = db.QueryRow("USE fortune500; SELECT * FROM `fortune500_2018_2022`").Scan(&dbName)
// if err != nil {
// log.Fatal("failed to execute query", err)
// }
// fmt.Println(dbName)
return c.JSON(fiber.Map{
"message": "connected to TiDB",
"connection": connection,
"db": db,
})
}