-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongo.go
102 lines (82 loc) · 2.24 KB
/
mongo.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package gom
import (
"context"
"fmt"
"log"
"reflect"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/bsontype"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
const (
// ScramSha1 is SCRAM-SHA-1 (legacy)
ScramSha1 = "SCRAM-SHA-1"
// ScramSha256 is SCRAM-SHA-256
ScramSha256 = "SCRAM-SHA-256"
// MongoDbCr is MONGODB-CR
MongoDbCr = "MONGODB-CR"
// Plain is PLAIN
Plain = "PLAIN"
// GssAPI is GSSAPI
GssAPI = "GSSAPI"
// MongoDbX509 is MONGODB-X509
MongoDbX509 = "MONGODB-X509"
)
// mongoDB = MongoDB struct
type mongoDB struct {
Config Config
Client *mongo.Client
Collection *mongo.Collection
ConnectionString string
}
// Config = Mongo config struct
type Config struct {
Username string
Password string
Host string
Port int
Database string
MaxPool int
AuthMechanism string
RegistryBuilder bool
}
// newMongo = Init new mongo
func newMongo() *mongoDB {
return new(mongoDB)
}
// SetConfig = Set config of mongo
func (m *mongoDB) SetConfig(config Config) {
m.Config = config
}
// SetClient = Set client
func (m *mongoDB) SetClient() {
config := m.Config
connectionString := fmt.Sprintf("mongodb://%s:%v", config.Host, config.Port)
if config.Username != "" {
connectionString = fmt.Sprintf("mongodb://%s:%s@%s:%v", config.Username, config.Password, config.Host, config.Port)
if config.AuthMechanism != "" {
connectionString = fmt.Sprintf("mongodb+srv://%s:%s@%s/%s?authMechanism=%s", config.Username, config.Password, config.Host, config.Database, config.AuthMechanism)
}
}
clientOptions := options.Client().ApplyURI(connectionString)
if config.MaxPool > 0 {
clientOptions.SetMaxPoolSize(uint64(config.MaxPool))
}
if config.RegistryBuilder {
// register custom codec registry to handle empty interfaces
rb := bson.NewRegistryBuilder()
rb.RegisterTypeMapEntry(bsontype.EmbeddedDocument, reflect.TypeOf(bson.M{}))
clientOptions.SetRegistry(rb.Build())
}
client, err := mongo.NewClient(clientOptions)
if err != nil {
log.Fatal(err)
}
err = client.Connect(context.Background())
if err != nil {
log.Fatal(err)
}
m.ConnectionString = connectionString
m.Client = client
}