db.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package global
  2. import (
  3. "bigdata_archives/configs"
  4. "fmt"
  5. "gorm.io/driver/mysql"
  6. "gorm.io/gorm"
  7. "gorm.io/gorm/logger"
  8. "log"
  9. "runtime"
  10. )
  11. var (
  12. DBLink *gorm.DB
  13. )
  14. func SetupDBLink() error {
  15. var err error
  16. dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?%s",
  17. configs.Config.GetString("database.userName"),
  18. configs.Config.GetString("database.password"),
  19. configs.Config.GetString("database.host"),
  20. configs.Config.GetString("database.db"),
  21. configs.Config.GetString("database.otherParams"),
  22. )
  23. //判断当前系统是windows还是linux
  24. //runtime获取的是当前Go语言框架的参数,不是实际运行的操作系统的参数
  25. sysType := runtime.GOOS
  26. if sysType == "windows" {
  27. DBLink, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
  28. DisableForeignKeyConstraintWhenMigrating: true,
  29. Logger: logger.Default.LogMode(logger.Info),
  30. })
  31. log.Print("当前系统为windows")
  32. } else if sysType == "linux" {
  33. DBLink, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
  34. }
  35. if err != nil {
  36. return err
  37. }
  38. return nil
  39. }