/
mongo.go
73 lines (59 loc) · 1.69 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
package mongo
import (
"context"
_ "github.com/golang-migrate/migrate/v4/database/mongodb"
_ "github.com/johejo/golang-migrate-extra/source/file"
"github.com/spf13/viper"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"go.opentelemetry.io/contrib/instrumentation/go.mongodb.org/mongo-driver/mongo/otelmongo"
storeOptions "github.com/shortlink-org/shortlink/pkg/db/options"
)
// Init - initialize
func (s *Store) Init(ctx context.Context) error {
var err error
// Set configuration
s.setConfig()
// Connect to MongoDB
opts := options.Client().
ApplyURI(s.config.URI).
SetCompressors([]string{"snappy", "zlib", "zstd"}).
SetAppName(viper.GetString("SERVICE_NAME")).
SetMonitor(otelmongo.NewMonitor()).
SetRetryReads(true).
SetRetryWrites(true)
s.client, err = mongo.Connect(ctx, opts)
if err != nil {
return err
}
// Check connect
err = s.client.Ping(ctx, readpref.Primary())
if err != nil {
return err
}
// Graceful shutdown
go func() {
<-ctx.Done()
_ = s.close(ctx)
}()
return nil
}
// GetConn - get connect
func (s *Store) GetConn() any {
return s.client
}
// Close - close
func (s *Store) close(ctx context.Context) error {
return s.client.Disconnect(ctx)
}
// setConfig - set configuration
func (s *Store) setConfig() {
viper.AutomaticEnv()
viper.SetDefault("STORE_MONGODB_URI", "mongodb://shortlink:password@localhost:27017/shortlink") // MongoDB URI
viper.SetDefault("STORE_MODE_WRITE", storeOptions.MODE_SINGLE_WRITE) // mode write to db
s.config = Config{
URI: viper.GetString("STORE_MONGODB_URI"),
mode: viper.GetInt("STORE_MODE_WRITE"),
}
}