|
| 1 | +package mongoconnect |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "context" |
| 6 | + "time" |
| 7 | + "go.mongodb.org/mongo-driver/mongo" |
| 8 | + "go.mongodb.org/mongo-driver/mongo/options" |
| 9 | + "go.mongodb.org/mongo-driver/mongo/readpref" |
| 10 | +) |
| 11 | + |
| 12 | + |
| 13 | +// This is a user defined method to close resources. |
| 14 | +// This method closes mongoDB connection and cancel context. |
| 15 | +func Close(client *mongo.Client, ctx context.Context, |
| 16 | + cancel context.CancelFunc){ |
| 17 | + |
| 18 | +// CancelFunc to cancel to context |
| 19 | +defer cancel() |
| 20 | + |
| 21 | +// client provides a method to close |
| 22 | +// a mongoDB connection. |
| 23 | +defer func(){ |
| 24 | + |
| 25 | + // client.Disconnect method also has deadline. |
| 26 | + // returns error if any, |
| 27 | + if err := client.Disconnect(ctx); err != nil{ |
| 28 | + panic(err) |
| 29 | + } |
| 30 | +}() |
| 31 | +} |
| 32 | + |
| 33 | +// This is a user defined method that returns mongo.Client, |
| 34 | +// context.Context, context.CancelFunc and error. |
| 35 | +// mongo.Client will be used for further database operation. |
| 36 | +// context.Context will be used set deadlines for process. |
| 37 | +// context.CancelFunc will be used to cancel context and |
| 38 | +// resource associated with it. |
| 39 | + |
| 40 | +func Connect(uri string)(*mongo.Client, context.Context, |
| 41 | + context.CancelFunc, error) { |
| 42 | + |
| 43 | +// ctx will be used to set deadline for process, here |
| 44 | +// deadline will of 30 seconds. |
| 45 | +ctx, cancel := context.WithTimeout(context.Background(), |
| 46 | + 30 * time.Second) |
| 47 | + |
| 48 | +// mongo.Connect return mongo.Client method |
| 49 | +client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri)) |
| 50 | +return client, ctx, cancel, err |
| 51 | +} |
| 52 | + |
| 53 | +// This is a user defined method that accepts |
| 54 | +// mongo.Client and context.Context |
| 55 | +// This method used to ping the mongoDB, return error if any. |
| 56 | +func Ping(client *mongo.Client, ctx context.Context) error{ |
| 57 | + |
| 58 | +// mongo.Client has Ping to ping mongoDB, deadline of |
| 59 | +// the Ping method will be determined by cxt |
| 60 | +// Ping method return error if any occurred, then |
| 61 | +// the error can be handled. |
| 62 | +if err := client.Ping(ctx, readpref.Primary()); err != nil { |
| 63 | + return err |
| 64 | +} |
| 65 | +fmt.Println("connected successfully") |
| 66 | +return nil |
| 67 | +} |
0 commit comments