update connect opts - add read pref mode #4

Merged
luuvansinh merged 1 commits from update-connect-opts into master 2022-03-03 02:30:30 +00:00
1 changed files with 14 additions and 1 deletions

View File

@ -25,6 +25,7 @@ type ConnectTLSOpts struct {
CaFile string CaFile string
CertKeyFile string CertKeyFile string
CertKeyFilePassword string CertKeyFilePassword string
ReadPreferenceMode string
} }
// ConnectStandaloneOpts ... // ConnectStandaloneOpts ...
@ -83,7 +84,7 @@ func connectWithTLS(cfg Config) (*mongo.Database, error) {
pwd := base64DecodeToString(opts.CertKeyFilePassword) pwd := base64DecodeToString(opts.CertKeyFilePassword)
s := "%s/?tls=true&tlsCAFile=./%s&tlsCertificateKeyFile=./%s&tlsCertificateKeyFilePassword=%s&authMechanism=MONGODB-X509" s := "%s/?tls=true&tlsCAFile=./%s&tlsCertificateKeyFile=./%s&tlsCertificateKeyFilePassword=%s&authMechanism=MONGODB-X509"
uri := fmt.Sprintf(s, cfg.Host, caFile.Name(), certFile.Name(), pwd) 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) clientOpts := options.Client().SetReadPreference(readPref).SetReplicaSet(opts.ReplSet).ApplyURI(uri)
client, err := mongo.Connect(ctx, clientOpts) client, err := mongo.Connect(ctx, clientOpts)
if err != nil { if err != nil {
@ -102,3 +103,15 @@ func connectWithTLS(cfg Config) (*mongo.Database, error) {
func GetInstance() *mongo.Database { func GetInstance() *mongo.Database {
return db 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
}