Files
mayfly-go/server/internal/mongo/mgm/conn.go
davidathena 4e30bdb7cc !138 fix: 后端数据连接断开后报空指针异常后程序中断问题
* fix(connection):fix the bug for nil error in connection when connection reset
* fix(sqleditor): fix the spell error in sql editor
2025-10-18 03:15:25 +00:00

43 lines
800 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package mgm
import (
"context"
"fmt"
"mayfly-go/pkg/logx"
"go.mongodb.org/mongo-driver/v2/mongo"
)
type MongoConn struct {
Id string
Info *MongoInfo
Cli *mongo.Client
}
/******************* pool.Conn impl *******************/
func (mc *MongoConn) Close() error {
if mc.Cli != nil {
if err := mc.Cli.Disconnect(context.Background()); err != nil {
logx.Errorf("关闭mongo实例[%s]连接失败: %s", mc.Id, err)
return err
}
mc.Cli = nil
}
return nil
}
func (mc *MongoConn) Ping() error {
// 首先检查mc是否为nil
if mc == nil {
return fmt.Errorf("mc connection is nil")
}
// 然后检查mc.Cli是否为nil这是避免空指针异常的关键
if mc.Cli == nil {
return fmt.Errorf("mc client is nil")
}
return mc.Cli.Ping(context.Background(), nil)
}