package mongo import ( "context" "datart/config" "strings" "time" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options" ) var client *mongo.Client func init() { conf := config.Conf().MongoConf("default") uri := "mongodb://" + strings.Join(conf.GetAddrs(), ",") cliOpts := options.Client(). ApplyURI(uri).SetTimeout(1 * time.Second). SetAuth(options.Credential{ AuthMechanism: conf.GetAuthMechanism(), AuthSource: conf.GetAuthSource(), Username: conf.GetUsername(), Password: conf.GetPassword(), }) cli, err := mongo.Connect(cliOpts) if err != nil { panic(err) } client = cli ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) defer cancel() if err := client.Ping(ctx, nil); err != nil { panic(err) } } func NewMongoClient(opts ...*options.ClientOptions) (*mongo.Client, error) { return mongo.Connect(opts...) } func Disconnect(ctx context.Context) error { return client.Disconnect(ctx) } func GetSession() (*mongo.Session, error) { return client.StartSession() } func getCollection(db string, tb string) *mongo.Collection { return client.Database(db).Collection(tb) }