global_db.go 873 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package dao
  2. import (
  3. "Zythum/config"
  4. _ "github.com/go-sql-driver/mysql"
  5. "github.com/jmoiron/sqlx"
  6. "gopkg.in/yaml.v3"
  7. "os"
  8. )
  9. var (
  10. db *sqlx.DB
  11. )
  12. func init() {
  13. data, err := os.ReadFile("config/datasource.yaml")
  14. if err != nil {
  15. panic("Failed to read datasource.yaml, please check the file.")
  16. }
  17. var dbConfig config.DBConfig
  18. err = yaml.Unmarshal(data, &dbConfig)
  19. if err != nil {
  20. panic("Failed to unmarshal datasource.yaml, please check the file.")
  21. }
  22. dsn := dbConfig.MySQLConfig.User + ":" +
  23. dbConfig.MySQLConfig.Password + "@tcp(" +
  24. dbConfig.MySQLConfig.Host + ":" +
  25. dbConfig.MySQLConfig.Port + ")/" +
  26. dbConfig.MySQLConfig.Database + "?charset=utf8mb4&parseTime=True"
  27. db, err = sqlx.Open("mysql", dsn)
  28. if err != nil {
  29. panic("Failed to connect database, please check the configuration.")
  30. }
  31. db.SetMaxOpenConns(30)
  32. db.SetMaxIdleConns(15)
  33. }