/
db.go
105 lines (87 loc) · 2.19 KB
/
db.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
103
104
105
package store
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"log"
"os"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"github.com/bananaops/tracker/internal/config"
)
// MongoClient is used to interact with features
type MongoClient struct {
collection *mongo.Collection
}
var caCertPool *x509.CertPool
var cert tls.Certificate
func NewClient(collection string) (c *mongo.Collection) {
config := config.ConfigDatabase
var m *mongo.Client
var err error
uri := createMongoUri(config)
ctx := context.Background()
if config.CAFile != "" {
tlsConfig := loadTlsCerts(config)
m, err = mongo.Connect(ctx, options.Client().ApplyURI(uri).SetTLSConfig(tlsConfig))
if err != nil {
log.Fatalf("error connect db %s", err)
}
} else {
m, err = mongo.Connect(ctx, options.Client().ApplyURI(uri))
if err != nil {
log.Fatalf("error connect db %s", err)
}
}
// init client collection
db := m.Database(config.Name)
err = db.CreateCollection(ctx, collection)
if err != nil {
log.Fatalf("error create collection %s", err)
}
return db.Collection(collection)
}
func loadTlsCerts(config config.Database) (tlsConfig *tls.Config) {
// Loads CA certificate file
caCert, err := os.ReadFile(config.CAFile)
if err != nil {
panic(err)
}
caCertPool = x509.NewCertPool()
if ok := caCertPool.AppendCertsFromPEM(caCert); !ok {
panic("Error: CA file must be in PEM format")
}
// Loads client certificate files
if config.CertFile != "" && config.KeyFile != "" {
cert, err = tls.LoadX509KeyPair(config.CertFile, config.KeyFile)
if err != nil {
panic(err)
}
}
return &tls.Config{
RootCAs: caCertPool,
Certificates: []tls.Certificate{cert},
MinVersion: tls.VersionTLS13,
}
}
func createMongoUri(config config.Database) (uri string) {
// prepare the uri for the connection
if config.Username != "" && config.Password != "" {
return fmt.Sprintf(
"mongodb://%s:%s@%s:%s/%s?maxPoolSize=20&tls=true&authMechanism=PLAIN",
config.Username,
config.Password,
config.Host,
config.Port,
config.Name,
)
} else {
return fmt.Sprintf(
"mongodb://%s:%s/%s?maxPoolSize=20",
config.Host,
config.Port,
config.Name,
)
}
}