github.com/aaabigfish/gopkg@v1.1.0/database/mongo/client.go (about)

     1  package mongo
     2  
     3  import (
     4  	"context"
     5  	"time"
     6  
     7  	"go.mongodb.org/mongo-driver/mongo"
     8  	"go.mongodb.org/mongo-driver/mongo/options"
     9  	"go.mongodb.org/mongo-driver/mongo/readpref"
    10  )
    11  
    12  var (
    13  	MC *mongo.Client
    14  )
    15  
    16  const (
    17  	defaultTimeout = 50 * time.Second
    18  	maxPoolSize    = 10
    19  )
    20  
    21  type Client struct {
    22  	C BaseCollection
    23  }
    24  
    25  func MongoClient(dbName, colName string, mc *mongo.Client) *Client {
    26  	dataBase := mc.Database(dbName)
    27  	c := &BaseCollectionImpl{
    28  		DbName:     dbName,
    29  		ColName:    colName,
    30  		DataBase:   dataBase,
    31  		Collection: dataBase.Collection(colName),
    32  	}
    33  	client := &Client{}
    34  	client.C = c
    35  	return client
    36  }
    37  
    38  func InitMongo(mongoUrl string) (*mongo.Client, error) {
    39  	var err error
    40  	ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout)
    41  	defer cancel()
    42  	MC, err = mongo.Connect(ctx, options.Client().ApplyURI(mongoUrl).SetMaxPoolSize(maxPoolSize))
    43  	if err != nil {
    44  		return nil, err
    45  	}
    46  	if err := MC.Ping(ctx, readpref.Primary()); err != nil {
    47  		return nil, err
    48  	}
    49  	return MC, nil
    50  }