codeword/pkg/mongo/connection.go

60 lines
1.3 KiB
Go
Raw Normal View History

2023-12-29 12:41:26 +00:00
package mongo
import (
"context"
"fmt"
"log"
"net"
"net/url"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type ConnectDeps struct {
Configuration *Configuration
Timeout time.Duration
}
func Connect(ctx context.Context, deps *ConnectDeps) (*mongo.Database, error) {
if deps == nil {
return nil, ErrEmptyArgs
}
mongoURI := &url.URL{
Scheme: "mongodb",
Host: net.JoinHostPort(deps.Configuration.MongoHost, deps.Configuration.MongoPort),
}
connectionOptions := options.Client().
ApplyURI(mongoURI.String()).
SetAuth(options.Credential{
2023-12-31 12:22:03 +00:00
AuthMechanism: "SCRAM-SHA-256",
2023-12-29 12:41:26 +00:00
AuthSource: deps.Configuration.MongoAuth,
Username: deps.Configuration.MongoUser,
Password: deps.Configuration.MongoPassword,
})
ticker := time.NewTicker(1 * time.Second)
timeoutExceeded := time.After(deps.Timeout)
defer ticker.Stop()
for {
select {
case <-ticker.C:
connection, err := mongo.Connect(ctx, connectionOptions)
if err == nil {
return connection.Database(deps.Configuration.MongoDatabase), nil
}
log.Printf("failed to connect to db <%s>: %s", mongoURI.String(), err.Error())
case <-timeoutExceeded:
return nil, fmt.Errorf("db connection <%s> failed after %d timeout", mongoURI.String(), deps.Timeout)
default:
time.Sleep(1 * time.Second)
}
}
}