71 lines
1.7 KiB
Go
71 lines
1.7 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"
|
||
|
|
)
|
||
|
|
|
||
|
|
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())
|
||
|
|
}
|
||
|
|
|
||
|
|
// 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
|
||
|
|
}
|