dataRT/data/mongo/mongo.go

55 lines
1.2 KiB
Go
Raw Normal View History

2025-09-19 16:17:46 +08:00
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{
2025-10-11 14:56:11 +08:00
AuthMechanism: conf.GetAuthMechanism(),
AuthSource: conf.GetAuthSource(),
2025-09-19 16:17:46 +08:00
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)
}
2025-11-06 21:09:50 +08:00
func GetSession() (*mongo.Session, error) {
return client.StartSession()
}
2025-09-19 16:17:46 +08:00
func getCollection(db string, tb string) *mongo.Collection {
return client.Database(db).Collection(tb)
}