package mongo import ( "context" "errors" "fmt" "time" newMongo "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "mongo.games.com/goserver/core/logger" ) var globalMongoSession *newMongo.Client func mongoURI(user, password, host string, port int32, options string) string { login := "" if user != "" { login = user + ":" + password + "@" } if host == "" { host = "localhost" } if port == 0 { port = 27017 } if options != "" { options = "?" + options } url := fmt.Sprintf("mongodb://%s%s:%d/admin%s", login, host, port, options) return url } // NewMongoClient 创建mongo客户端 // Deprecated: use [mongo.games.com/game/mongo] instead func NewMongoClient() (*newMongo.Client, error) { if globalMongoSession != nil { return globalMongoSession, nil } cfg, b := MgoSessionMgrSington.GetCfg(G_P, "user") if !b { return nil, errors.New("not db") } ctx, _ := context.WithTimeout(context.Background(), 5*time.Second) client, err := newMongo.Connect(ctx, options.Client().ApplyURI(mongoURI(cfg.Username, cfg.Password, cfg.HostName, cfg.HostPort, cfg.Options))) if err != nil { logger.Logger.Errorf("NewMongoClient error:%v", err) return nil, err } if client == nil { return nil, errors.New("not db client") } globalMongoSession = client return client, nil }