85 lines
2.0 KiB
Go
85 lines
2.0 KiB
Go
package mongo
|
||
|
||
import (
|
||
"context"
|
||
"errors"
|
||
"strings"
|
||
"time"
|
||
|
||
"go.mongodb.org/mongo-driver/mongo"
|
||
"go.mongodb.org/mongo-driver/mongo/options"
|
||
"go.mongodb.org/mongo-driver/mongo/readpref"
|
||
)
|
||
|
||
type Config struct {
|
||
Uri string
|
||
Username string
|
||
Password string
|
||
Database string
|
||
Timeout int
|
||
}
|
||
|
||
var config *Config
|
||
|
||
func Init(conf *Config) {
|
||
config = conf
|
||
if config == nil {
|
||
config = &Config{
|
||
Uri: "mongodb://localhost:27017",
|
||
Database: "admin",
|
||
Timeout: 3,
|
||
}
|
||
}
|
||
}
|
||
|
||
//New 获取mongo客户端
|
||
//// "mongodb://user:password@localhost:27017"
|
||
func New() (*mongo.Client, error) {
|
||
clientOpts := options.Client().ApplyURI(config.Uri)
|
||
|
||
if config.Username != "" && config.Password != "" {
|
||
clientOpts = clientOpts.SetAuth(options.Credential{
|
||
AuthMechanism: "SCRAM-SHA-256",
|
||
AuthSource: config.Database,
|
||
Username: config.Username,
|
||
Password: config.Password,
|
||
})
|
||
}
|
||
|
||
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(config.Timeout)*time.Second)
|
||
defer cancel()
|
||
|
||
return mongo.Connect(ctx, clientOpts)
|
||
}
|
||
|
||
func Ping() error {
|
||
client, err := New()
|
||
if err != nil {
|
||
return err
|
||
}
|
||
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(config.Timeout)*time.Second)
|
||
defer cancel()
|
||
defer client.Disconnect(ctx)
|
||
return client.Ping(ctx, readpref.Primary())
|
||
}
|
||
|
||
//Collection 获取集合
|
||
func Collection(client *mongo.Client, cname string) (*mongo.Collection, error) {
|
||
collection := client.Database(config.Database).Collection(cname)
|
||
return collection, nil
|
||
}
|
||
|
||
//CollectionMulti 支持多数据库直接获取collection
|
||
func CollectionMulti(client *mongo.Client, cname string) (*mongo.Collection, error) {
|
||
name := strings.Split(cname, ".")
|
||
if len(name) != 2 {
|
||
return nil, errors.New("collection名称不正确,请使用[database.collection]方式使用")
|
||
}
|
||
if name[0] == "" || name[1] == "" {
|
||
return nil, errors.New("名称不能为空")
|
||
}
|
||
|
||
collection := client.Database(name[0]).Collection(name[1])
|
||
return collection, nil
|
||
}
|