mysql_common.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package helpers
  2. import (
  3. "fmt"
  4. "github.com/spf13/viper"
  5. "gorm.io/driver/mysql"
  6. "gorm.io/gorm"
  7. "gorm.io/gorm/logger"
  8. )
  9. var (
  10. MasterDB *gorm.DB
  11. ReadDB *gorm.DB
  12. )
  13. func InitMysqlCommon(v *viper.Viper) {
  14. // TODO: Apply different databases.
  15. stage := getStage()
  16. if stage != "dev" && stage != "prod" && stage != "fork" {
  17. panic("Failed to check the stage.")
  18. }
  19. MasterDB = getWriteMasterDB(v)
  20. ReadDB = getReadReplicaDB(v)
  21. }
  22. func getWriteMasterDB(v *viper.Viper) *gorm.DB {
  23. host := v.GetString("db.writer")
  24. user := v.GetString("db.user")
  25. port := v.GetString("db.port")
  26. password := v.GetString("db.password")
  27. dbName := v.GetString("db.database")
  28. dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", user, password, host, port, dbName)
  29. WDB, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
  30. Logger: logger.Default.LogMode(logger.Info),
  31. })
  32. if err != nil {
  33. panic("failed to connect database")
  34. }
  35. return WDB
  36. }
  37. func getReadReplicaDB(v *viper.Viper) *gorm.DB {
  38. host := v.GetString("db.reader")
  39. user := v.GetString("db.user")
  40. port := v.GetString("db.port")
  41. password := v.GetString("db.password")
  42. dbName := v.GetString("db.database")
  43. dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", user, password, host, port, dbName)
  44. RDB, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
  45. if err != nil {
  46. panic("failed to connect database")
  47. }
  48. return RDB
  49. }