git.zd.zone/hrpc/hrpc@v0.0.12/database/mongodb/mongodb.go (about) 1 package mongodb 2 3 import ( 4 "context" 5 "encoding/json" 6 "fmt" 7 "time" 8 9 "git.zd.zone/hrpc/hrpc/database" 10 "go.mongodb.org/mongo-driver/mongo" 11 "go.mongodb.org/mongo-driver/mongo/options" 12 "go.mongodb.org/mongo-driver/mongo/readpref" 13 ) 14 15 func (o Options) URI() string { 16 return fmt.Sprintf("mongodb://%s:%s@%s", o.Username, o.Password, o.Address) 17 } 18 19 type MongoDB struct { 20 conn *mongo.Client 21 options Options 22 } 23 24 var m *MongoDB 25 26 func (m *MongoDB) Load(src []byte) error { 27 // If the value of customized is true (enabled), 28 // which means DOES NOT use the configurations from the configuration center. 29 if m.options.customized { 30 return nil 31 } 32 if err := json.Unmarshal(src, &m.options); err != nil { 33 return err 34 } 35 return nil 36 } 37 38 func (m *MongoDB) Connect() error { 39 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) 40 defer cancel() 41 client, err := mongo.Connect(ctx, options.Client().ApplyURI(m.options.URI())) 42 if err != nil { 43 return err 44 } 45 if err := client.Ping(ctx, readpref.Primary()); err != nil { 46 return err 47 } 48 m.conn = client 49 return nil 50 } 51 52 func (m *MongoDB) Destory() { 53 if m.conn != nil { 54 m.conn.Disconnect(context.Background()) 55 } 56 } 57 58 func Client() *mongo.Client { 59 return m.conn 60 } 61 62 func (m MongoDB) Name() string { 63 return "mongodb" 64 } 65 66 // Valid returns a bool valud to determine whether the connection is ready to use 67 func Valid() bool { 68 if m == nil { 69 return false 70 } 71 if m.conn == nil { 72 return false 73 } 74 if err := m.conn.Ping(context.Background(), readpref.Primary()); err != nil { 75 return false 76 } 77 return true 78 } 79 80 func New(opts ...Option) *MongoDB { 81 var options = Options{ 82 customized: false, 83 } 84 for _, o := range opts { 85 o(&options) 86 } 87 88 if m != nil { 89 m.Destory() 90 } 91 m = &MongoDB{ 92 options: options, 93 } 94 return m 95 } 96 97 var _ database.Database = (*MongoDB)(nil)