-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
48 lines (38 loc) · 1.32 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
package main
import (
"fmt"
"log"
proxy "github.com/GoogleCloudPlatform/cloudsql-proxy/proxy/dialers/mysql"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func main() {
ConnectToGCSMySQLDatabase()
}
func ConnectToGCSMySQLDatabase() *gorm.DB {
user := "username" // Username
passwd := "password" // Password
instance := "projectId:region:instance"
// ProjectID : This is the project ID or name. It identifies the Google Cloud project that contains the MySQL instance.
// Region: This is the region where the MySQL instance is located. In this case, it is the us-east1 region.
// Instace: This is the name of the MySQL instance within the specified project and region. It uniquely identifies the MySQL instance.
// Example : lazy-project:us-east-1:mysql-live
database := "database" // Dataabase name
cfg := proxy.Cfg(instance, user, passwd)
cfg.DBName = database
db, err := proxy.DialCfg(cfg)
if err != nil {
fmt.Println("failed to connect database")
panic("failed to connect database")
}
// In case you want to convert that connection to GORM
gormDB, err := gorm.Open(mysql.New(mysql.Config{
Conn: db,
}), &gorm.Config{})
if err != nil {
fmt.Println("failed to connect as a gorm database")
panic("failed to connect as gorm database")
}
log.Println("Successfully connected to MySQL database.")
return gormDB
}