123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- package helpers
- import (
- "fmt"
- "github.com/spf13/viper"
- "gorm.io/driver/mysql"
- "gorm.io/gorm"
- "gorm.io/gorm/logger"
- )
- var (
- MasterDB *gorm.DB
- ReadDB *gorm.DB
- )
- func InitMysqlCommon(v *viper.Viper) {
- // TODO: Apply different databases.
- stage := getStage()
- if stage != "dev" && stage != "prod" && stage != "fork" {
- panic("Failed to check the stage.")
- }
- MasterDB = getWriteMasterDB(v)
- ReadDB = getReadReplicaDB(v)
- }
- func getWriteMasterDB(v *viper.Viper) *gorm.DB {
- host := v.GetString("db.writer")
- user := v.GetString("db.user")
- port := v.GetString("db.port")
- password := v.GetString("db.password")
- dbName := v.GetString("db.database")
- dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", user, password, host, port, dbName)
- WDB, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
- Logger: logger.Default.LogMode(logger.Info),
- })
- if err != nil {
- panic("failed to connect database")
- }
- return WDB
- }
- func getReadReplicaDB(v *viper.Viper) *gorm.DB {
- host := v.GetString("db.reader")
- user := v.GetString("db.user")
- port := v.GetString("db.port")
- password := v.GetString("db.password")
- dbName := v.GetString("db.database")
- dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", user, password, host, port, dbName)
- RDB, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
- if err != nil {
- panic("failed to connect database")
- }
- return RDB
- }
|