-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
db: add mongodb client factory support
- Loading branch information
1 parent
cbeb3d3
commit 834f386
Showing
5 changed files
with
144 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
package mongokit | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"log" | ||
"net/url" | ||
|
||
"github.com/adipurnama/go-toolkit/db" | ||
"go.mongodb.org/mongo-driver/mongo" | ||
"go.mongodb.org/mongo-driver/mongo/options" | ||
) | ||
|
||
// NewMongoDBClient returns new mongodb client using the go mongo-driver | ||
func NewMongoDBClient(opt *db.Option) (*mongo.Client, error) { | ||
connURL := &url.URL{ | ||
Scheme: "mongodb", | ||
User: url.UserPassword(opt.Username, opt.Password), | ||
Host: fmt.Sprintf("%s:%d", opt.Host, opt.Port), | ||
} | ||
q := connURL.Query() | ||
q.Add("authSource", opt.DatabaseName) | ||
connURL.RawQuery = q.Encode() | ||
|
||
clientOptions := options.Client() | ||
clientOptions.ApplyURI(connURL.String()) | ||
clientOptions.SetConnectTimeout(opt.ConnectionOption.ConnectTimeout) | ||
clientOptions.SetMaxConnIdleTime(opt.ConnectionOption.MaxLifetime) | ||
clientOptions.SetMaxPoolSize(uint64(opt.ConnectionOption.MaxOpen)) | ||
|
||
client, err := mongo.NewClient(clientOptions) | ||
if err != nil { | ||
log.Fatalf("Cannot create MongoDB client: %s", err) | ||
} | ||
|
||
ctx, cancel := context.WithTimeout(context.Background(), opt.ConnectionOption.ConnectTimeout) | ||
defer cancel() | ||
|
||
err = client.Connect(ctx) | ||
|
||
return client, err | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.