Compare commits

..

12 Commits

Author SHA1 Message Date
sinhluu 92d420a643 Merge pull request 'add func convert' (#8) from add-convert into master
Reviewed-on: #8
2022-12-14 10:07:24 +00:00
anbuiselly 008506a181 fix 2022-12-14 15:55:03 +07:00
anbuiselly 6dc437b245 fix 2022-12-14 15:53:45 +07:00
anbuiselly 384922ab68 add func convert 2022-12-14 15:49:46 +07:00
trunglt251292 1d897a0f9e [Update] Package name 2022-10-10 10:37:54 +07:00
Sinh Luu 438cfd8b9c
Merge pull request #7 from Selly-Modules/support-uri-with-options
support uri with options
2022-06-16 14:22:19 +07:00
Sinh 2b279769e6 support uri with options 2022-06-16 14:21:34 +07:00
luuvansinh 1daf5b3f1e
Merge pull request #6 from Selly-Modules/add-monitor
add monitor options
2022-03-14 10:34:05 +07:00
Sinh 47978662ca add monitor options 2022-03-14 10:31:44 +07:00
luuvansinh 880bc3d937
Merge pull request #5 from Selly-Modules/add-monitor
add monitor options
2022-03-04 20:15:03 +07:00
Sinh 29e892b420 add monitor options 2022-03-04 20:14:30 +07:00
luuvansinh 3e29ed42b1
Merge pull request #4 from Selly-Modules/update-connect-opts
update connect opts - add read pref mode
2022-03-03 09:30:30 +07:00
5 changed files with 133 additions and 6 deletions

42
convert.go Normal file
View File

@ -0,0 +1,42 @@
package mongodb
import (
"github.com/thoas/go-funk"
"go.mongodb.org/mongo-driver/bson/primitive"
"sort"
)
// ConvertObjectIDsToStrings ...
func ConvertObjectIDsToStrings(ids []primitive.ObjectID) []string {
return funk.Map(ids, func(item primitive.ObjectID) string {
return item.Hex()
}).([]string)
}
// UniqObjectIds ...
func UniqObjectIds(ids []primitive.ObjectID) []primitive.ObjectID {
idStr := ConvertObjectIDsToStrings(ids)
idStr = funk.UniqString(idStr)
return ConvertStringsToObjectIDs(idStr)
}
// ConvertStringsToObjectIDs ...
func ConvertStringsToObjectIDs(strValues []string) []primitive.ObjectID {
return funk.Map(strValues, func(item string) primitive.ObjectID {
return ConvertStringToObjectID(item)
}).([]primitive.ObjectID)
}
// ConvertStringToObjectID ...
func ConvertStringToObjectID(id string) primitive.ObjectID {
objID, _ := primitive.ObjectIDFromHex(id)
return objID
}
// SortObjectId ...
func SortObjectId(ids []primitive.ObjectID) []primitive.ObjectID {
sort.Slice(ids, func(i, j int) bool {
return ids[i].Timestamp().Before(ids[j].Timestamp())
})
return ids
}

3
go.mod
View File

@ -1,9 +1,10 @@
module github.com/Selly-Modules/mongodb
module git.selly.red/Selly-Modules/mongodb
go 1.16
require (
github.com/logrusorgru/aurora v2.0.3+incompatible
github.com/thoas/go-funk v0.9.2 // indirect
go.mongodb.org/mongo-driver v1.7.1
golang.org/x/text v0.3.7
)

4
go.sum
View File

@ -67,8 +67,11 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/thoas/go-funk v0.9.2 h1:oKlNYv0AY5nyf9g+/GhMgS/UO2ces0QRdPKwkhY3VCk=
github.com/thoas/go-funk v0.9.2/go.mod h1:+IWnUfUmFO1+WVYQWQtIJHeRRdaIyyYglZN7xzUPe4Q=
github.com/tidwall/pretty v1.0.0 h1:HsD+QiTn7sK6flMKIvNmpqz1qrpP3Ps6jOKIKMooyg4=
github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c=
@ -114,6 +117,7 @@ golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8T
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@ -3,8 +3,10 @@ package mongodb
import (
"context"
"fmt"
"strings"
"github.com/logrusorgru/aurora"
"go.mongodb.org/mongo-driver/event"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
@ -14,6 +16,7 @@ import (
type Config struct {
Host string
DBName string
Monitor *event.CommandMonitor
TLS *ConnectTLSOpts
Standalone *ConnectStandaloneOpts
@ -46,7 +49,7 @@ func Connect(cfg Config) (*mongo.Database, error) {
connectOptions := options.ClientOptions{}
opts := cfg.Standalone
// Set auth if existed
if opts.Username != "" && opts.Password != "" {
if opts != nil && opts.Username != "" && opts.Password != "" {
connectOptions.Auth = &options.Credential{
AuthMechanism: opts.AuthMechanism,
AuthSource: opts.AuthSource,
@ -54,6 +57,9 @@ func Connect(cfg Config) (*mongo.Database, error) {
Password: opts.Password,
}
}
if cfg.Monitor != nil {
connectOptions.SetMonitor(cfg.Monitor)
}
// Connect
client, err := mongo.Connect(context.Background(), connectOptions.ApplyURI(cfg.Host))
@ -82,10 +88,12 @@ func connectWithTLS(cfg Config) (*mongo.Database, error) {
return nil, err
}
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)
uri := getURIWithTLS(cfg, caFile.Name(), certFile.Name(), pwd)
readPref := getReadPref(opts.ReadPreferenceMode)
clientOpts := options.Client().SetReadPreference(readPref).SetReplicaSet(opts.ReplSet).ApplyURI(uri)
if cfg.Monitor != nil {
clientOpts.SetMonitor(cfg.Monitor)
}
client, err := mongo.Connect(ctx, clientOpts)
if err != nil {
return nil, err
@ -99,6 +107,22 @@ func connectWithTLS(cfg Config) (*mongo.Database, error) {
return db, err
}
func getURIWithTLS(cfg Config, caFilePath, certFilePath, pwd string) string {
host := cfg.Host
if strings.Contains(host, "?") {
host += "&"
} else {
if !strings.HasSuffix(host, "/") {
host += "/?"
} else {
host += "?"
}
}
s := "%stls=true&tlsCAFile=./%s&tlsCertificateKeyFile=./%s&tlsCertificateKeyFilePassword=%s&authMechanism=MONGODB-X509"
uri := fmt.Sprintf(s, host, caFilePath, certFilePath, pwd)
return uri
}
// GetInstance ...
func GetInstance() *mongo.Database {
return db

View File

@ -1,6 +1,7 @@
package mongodb
import (
"fmt"
"testing"
"go.mongodb.org/mongo-driver/mongo"
@ -45,3 +46,58 @@ func Test_connectWithTLS(t *testing.T) {
})
}
}
func Test_getURIWithTLS(t *testing.T) {
type args struct {
cfg Config
caFilePath string
certFilePath string
pwd string
}
ca := "ca.pem"
cert := "cert.pem"
pwd := "1"
tests := []struct {
name string
args args
want string
}{
{
name: "uri no options",
args: args{
cfg: Config{Host: "mongodb://localhost:27017"},
caFilePath: ca,
certFilePath: cert,
pwd: pwd,
},
want: fmt.Sprintf("mongodb://localhost:27017/?tls=true&tlsCAFile=./%s&tlsCertificateKeyFile=./%s&tlsCertificateKeyFilePassword=%s&authMechanism=MONGODB-X509", ca, cert, pwd),
},
{
name: "uri no options, end with /",
args: args{
cfg: Config{Host: "mongodb://localhost:27017/"},
caFilePath: ca,
certFilePath: cert,
pwd: pwd,
},
want: fmt.Sprintf("mongodb://localhost:27017/?tls=true&tlsCAFile=./%s&tlsCertificateKeyFile=./%s&tlsCertificateKeyFilePassword=%s&authMechanism=MONGODB-X509", ca, cert, pwd),
},
{
name: "uri has options",
args: args{
cfg: Config{Host: "mongodb://localhost:27017/?a=1"},
caFilePath: ca,
certFilePath: cert,
pwd: pwd,
},
want: fmt.Sprintf("mongodb://localhost:27017/?a=1&tls=true&tlsCAFile=./%s&tlsCertificateKeyFile=./%s&tlsCertificateKeyFilePassword=%s&authMechanism=MONGODB-X509", ca, cert, pwd),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := getURIWithTLS(tt.args.cfg, tt.args.caFilePath, tt.args.certFilePath, tt.args.pwd); got != tt.want {
t.Errorf("getURIWithTLS() = %v, want %v", got, tt.want)
}
})
}
}