-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathmongo.go
61 lines (48 loc) · 1.36 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
package mongoex
import (
"context"
"crypto/tls"
"errors"
"fmt"
"net/url"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
"github.com/circleci/ex/o11y"
"github.com/circleci/ex/rootcerts"
)
type Config struct {
URI string
UseTLS bool
Options *options.ClientOptions
}
// New connects to mongo. The context passed in is expected to carry an o11y provider
// and is only used for reporting (not for cancellation),
func New(ctx context.Context, appName string, cfg Config) (client *mongo.Client, err error) {
_, span := o11y.StartSpan(ctx, "cfg: connect to database")
defer o11y.End(span, &err)
mongoURL, err := url.Parse(cfg.URI)
// url.Parse will print the URI if it can't parse. The URI contains the password, so this gets the underlying error
// without printing the secret string.
var urlError *url.Error
if errors.As(err, &urlError) {
return nil, fmt.Errorf("mongoex: failed to parse URI: %w", urlError.Err)
} else if err != nil {
return nil, err
}
span.AddField("host", mongoURL.Host)
span.AddField("username", mongoURL.User)
opts := cfg.Options
if opts == nil {
opts = options.Client()
}
opts.
ApplyURI(cfg.URI).
SetAppName(appName)
if cfg.UseTLS {
opts = opts.SetTLSConfig(&tls.Config{
MinVersion: tls.VersionTLS12,
RootCAs: rootcerts.ServerCertPool(),
})
}
return mongo.Connect(opts)
}