gorm_client.go 859 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package mysql
  2. import (
  3. _ "github.com/go-sql-driver/mysql"
  4. "github.com/jinzhu/gorm"
  5. )
  6. type GormClient struct {
  7. master *gorm.DB
  8. slave *gorm.DB
  9. }
  10. func NewClient() *GormClient {
  11. return &GormClient{}
  12. }
  13. var Client *GormClient
  14. func Dial(dialect string, args ...interface{}) (*GormClient, error) {
  15. Client = NewClient()
  16. return Client.Dial(dialect, args...)
  17. }
  18. func (c *GormClient) Dial(dialect string, args ...interface{}) (*GormClient, error) {
  19. var err error
  20. // master dial
  21. c.master, err = gorm.Open(dialect, args...)
  22. if err != nil {
  23. return c, err
  24. }
  25. c.master.LogMode(true)
  26. c.master.Debug()
  27. // slave dial
  28. c.slave, err = gorm.Open(dialect, args...)
  29. if err != nil {
  30. return c, err
  31. }
  32. c.slave.LogMode(true)
  33. return c, nil
  34. }
  35. func (c *GormClient) Master() *gorm.DB {
  36. return c.master
  37. }
  38. func (c *GormClient) Slave() *gorm.DB {
  39. return c.slave
  40. }