38 lines
981 B
Go
38 lines
981 B
Go
package mongox
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"strings"
|
|
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
)
|
|
|
|
type Config struct {
|
|
Host string `json:"host"`
|
|
UserName string `json:"userName"`
|
|
Password string `json:"password"`
|
|
Database string `json:"dataBase"`
|
|
}
|
|
|
|
func Connect(ctx context.Context, cfg Config) (*mongo.Client, *mongo.Database, error) {
|
|
uri := cfg.Host
|
|
if !strings.HasPrefix(uri, "mongodb://") && !strings.HasPrefix(uri, "mongodb+srv://") {
|
|
uri = "mongodb://" + uri
|
|
}
|
|
opts := options.Client().ApplyURI(uri)
|
|
if cfg.UserName != "" {
|
|
opts.SetAuth(options.Credential{Username: cfg.UserName, Password: cfg.Password})
|
|
}
|
|
client, err := mongo.Connect(ctx, opts)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("connect mongodb: %w", err)
|
|
}
|
|
if err := client.Ping(ctx, nil); err != nil {
|
|
_ = client.Disconnect(ctx)
|
|
return nil, nil, fmt.Errorf("ping mongodb: %w", err)
|
|
}
|
|
return client, client.Database(cfg.Database), nil
|
|
}
|