dbhelper.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * @description:
  3. * @Author: CP
  4. * @Date: 2020-08-20 22:25:17
  5. * @FilePath: \construction_management\datasource\dbhelper.go
  6. */
  7. package datasource
  8. import (
  9. "fmt"
  10. "log"
  11. "sync"
  12. _ "github.com/go-sql-driver/mysql"
  13. "github.com/go-xorm/xorm"
  14. "github.com/spf13/viper"
  15. "go.mod/conf"
  16. )
  17. //互斥锁
  18. var dbLock sync.Mutex
  19. var masterInstance *xorm.Engine
  20. //单例模式
  21. func InstanceDbMaster() *xorm.Engine {
  22. if masterInstance != nil {
  23. return masterInstance
  24. }
  25. dbLock.Lock()
  26. defer dbLock.Unlock()
  27. if masterInstance != nil {
  28. return masterInstance
  29. }
  30. return NewDbMaster()
  31. }
  32. func GetEnvInfo(env string) bool {
  33. viper.AutomaticEnv()
  34. return viper.GetBool(env)
  35. }
  36. func NewDbMaster() *xorm.Engine {
  37. debug := GetEnvInfo("Debug")
  38. configFilePrefix := "config"
  39. configFileName := fmt.Sprintf("%s-pro.yaml", configFilePrefix)
  40. fmt.Println(debug)
  41. if debug {
  42. configFileName = fmt.Sprintf("%s-debug.yaml", configFilePrefix)
  43. }
  44. v := viper.New()
  45. v.SetConfigFile(configFileName)
  46. if err := v.ReadInConfig(); err != nil {
  47. log.Fatal("读取配置文件出错:", err)
  48. return nil
  49. }
  50. if err := v.Unmarshal(&conf.MysqlConfig); err != nil {
  51. panic(err)
  52. }
  53. sourcename := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8",
  54. conf.MysqlConfig.User,
  55. conf.MysqlConfig.Pwd,
  56. conf.MysqlConfig.Host,
  57. conf.MysqlConfig.Port,
  58. conf.MysqlConfig.Datebase)
  59. instance, err := xorm.NewEngine(conf.DriverName, sourcename)
  60. if err != nil {
  61. log.Fatal("dbhelper.NewDbMaster NewEngine error ", err)
  62. return nil
  63. }
  64. //展示执行的sql语句
  65. instance.ShowSQL(true)
  66. masterInstance = instance
  67. return instance
  68. }