From 6e0cbfd1417615b9b336bb76db5533f281fdf678 Mon Sep 17 00:00:00 2001 From: Sinh Date: Thu, 3 Mar 2022 09:29:04 +0700 Subject: [PATCH] update connect opts - add read pref mode --- mongodb.go | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/mongodb.go b/mongodb.go index f83c888..53c7b43 100644 --- a/mongodb.go +++ b/mongodb.go @@ -25,6 +25,7 @@ type ConnectTLSOpts struct { CaFile string CertKeyFile string CertKeyFilePassword string + ReadPreferenceMode string } // ConnectStandaloneOpts ... @@ -83,7 +84,7 @@ func connectWithTLS(cfg Config) (*mongo.Database, error) { pwd := base64DecodeToString(opts.CertKeyFilePassword) s := "%s/?tls=true&tlsCAFile=./%s&tlsCertificateKeyFile=./%s&tlsCertificateKeyFilePassword=%s&authMechanism=MONGODB-X509" uri := fmt.Sprintf(s, cfg.Host, caFile.Name(), certFile.Name(), pwd) - readPref := readpref.SecondaryPreferred() + readPref := getReadPref(opts.ReadPreferenceMode) clientOpts := options.Client().SetReadPreference(readPref).SetReplicaSet(opts.ReplSet).ApplyURI(uri) client, err := mongo.Connect(ctx, clientOpts) if err != nil { @@ -102,3 +103,15 @@ func connectWithTLS(cfg Config) (*mongo.Database, error) { func GetInstance() *mongo.Database { return db } + +func getReadPref(mode string) *readpref.ReadPref { + m, err := readpref.ModeFromString(mode) + if err != nil { + m = readpref.SecondaryPreferredMode + } + readPref, err := readpref.New(m) + if err != nil { + fmt.Println("mongodb.getReadPref err: ", err, m) + } + return readPref +} -- 2.34.1