add tls connect options

This commit is contained in:
Sinh 2022-02-24 15:00:42 +07:00
parent 2b6be44627
commit 98893c5c57
5 changed files with 153 additions and 43 deletions

3
.gitignore vendored
View File

@ -14,4 +14,5 @@
# Dependency directories (remove the comment below to include it) # Dependency directories (remove the comment below to include it)
# vendor/ # vendor/
.idea .idea
*.pem

12
base64.go Normal file
View File

@ -0,0 +1,12 @@
package mongodb
import "encoding/base64"
func base64DecodeToBytes(text string) []byte {
s, _ := base64.StdEncoding.DecodeString(text)
return s
}
func base64DecodeToString(text string) string {
return string(base64DecodeToBytes(text))
}

View File

@ -10,27 +10,81 @@ import (
"go.mongodb.org/mongo-driver/mongo/readpref" "go.mongodb.org/mongo-driver/mongo/readpref"
) )
// Config ...
type Config struct {
Host string
DBName string
TLS *ConnectTLSOpts
Standalone *ConnectStandaloneOpts
}
// ConnectTLSOpts ... // ConnectTLSOpts ...
type ConnectTLSOpts struct { type ConnectTLSOpts struct {
Host string ReplSet string
DBName string CaFile string
ReplSet string CertKeyFile string
CaFilePath string CertKeyFilePassword string
CertificateKeyFilePath string }
CertificateKeyFilePassword string
// ConnectStandaloneOpts ...
type ConnectStandaloneOpts struct {
AuthMechanism string
AuthSource string
Username string
Password string
} }
var db *mongo.Database var db *mongo.Database
// ConnectWithTLS ... // Connect to mongo server
func ConnectWithTLS(opts ConnectTLSOpts) (*mongo.Database, error) { func Connect(cfg Config) (*mongo.Database, error) {
ctx := context.Background() if cfg.TLS != nil && cfg.TLS.ReplSet != "" {
uri := fmt.Sprintf("%s/?tls=true&tlsCAFile=%s&tlsCertificateKeyFile=%s&tlsCertificateKeyFilePassword=%s", opts.Host, opts.CaFilePath, opts.CertificateKeyFilePath, opts.CertificateKeyFilePassword) return connectWithTLS(cfg)
readPref := readpref.SecondaryPreferred()
credential := options.Credential{
AuthMechanism: "MONGODB-X509",
} }
clientOpts := options.Client().SetAuth(credential).SetReadPreference(readPref).SetReplicaSet(opts.ReplSet).ApplyURI(uri) connectOptions := options.ClientOptions{}
opts := cfg.Standalone
// Set auth if existed
if opts.Username != "" && opts.Password != "" {
connectOptions.Auth = &options.Credential{
AuthMechanism: opts.AuthMechanism,
AuthSource: opts.AuthSource,
Username: opts.Username,
Password: opts.Password,
}
}
// Connect
client, err := mongo.Connect(context.Background(), connectOptions.ApplyURI(cfg.Host))
if err != nil {
fmt.Println("Error when connect to MongoDB database", cfg.Host, err)
return nil, err
}
fmt.Println(aurora.Green("*** CONNECTED TO MONGODB: " + cfg.Host + " --- DB: " + cfg.DBName))
// Set data
db = client.Database(cfg.DBName)
return db, nil
}
func connectWithTLS(cfg Config) (*mongo.Database, error) {
ctx := context.Background()
opts := cfg.TLS
caFile, err := initFileFromBase64String("ca.pem", opts.CaFile)
if err != nil {
return nil, err
}
certFile, err := initFileFromBase64String("cert.pem", opts.CertKeyFile)
if err != nil {
return nil, err
}
pwd := base64DecodeToString(opts.CertKeyFilePassword)
s := "%s/?tls=true&tlsCAFile=./%s&tlsCertificateKeyFile=./%s&tlsCertificateKeyFilePassword=%s&authMechanism=MONGODB-X509"
uri := fmt.Sprintf(s, cfg.Host, caFile.Name(), certFile.Name(), pwd)
readPref := readpref.SecondaryPreferred()
clientOpts := options.Client().SetReadPreference(readPref).SetReplicaSet(opts.ReplSet).ApplyURI(uri)
client, err := mongo.Connect(ctx, clientOpts) client, err := mongo.Connect(ctx, clientOpts)
if err != nil { if err != nil {
return nil, err return nil, err
@ -38,37 +92,12 @@ func ConnectWithTLS(opts ConnectTLSOpts) (*mongo.Database, error) {
if err := client.Ping(ctx, readpref.SecondaryPreferred()); err != nil { if err := client.Ping(ctx, readpref.SecondaryPreferred()); err != nil {
return nil, err return nil, err
} }
db = client.Database(opts.DBName) db = client.Database(cfg.DBName)
fmt.Println(aurora.Green("*** CONNECTED TO MONGODB: " + cfg.Host + " --- DB: " + cfg.DBName))
return db, err return db, err
} }
// Connect to mongo server
func Connect(host, user, password, dbName, mechanism, source string) (*mongo.Database, error) {
connectOptions := options.ClientOptions{}
// Set auth if existed
if user != "" && password != "" {
connectOptions.Auth = &options.Credential{
AuthMechanism: mechanism,
AuthSource: source,
Username: user,
Password: password,
}
}
// Connect
client, err := mongo.Connect(context.Background(), connectOptions.ApplyURI(host))
if err != nil {
fmt.Println("Error when connect to MongoDB database", host, err)
return nil, err
}
fmt.Println(aurora.Green("*** CONNECTED TO MONGODB: " + host + " --- DB: " + dbName))
// Set data
db = client.Database(dbName)
return db, nil
}
// GetInstance ... // GetInstance ...
func GetInstance() *mongo.Database { func GetInstance() *mongo.Database {
return db return db

47
mongodb_test.go Normal file

File diff suppressed because one or more lines are too long

21
util.go Normal file
View File

@ -0,0 +1,21 @@
package mongodb
import (
"fmt"
"os"
)
func initFileFromBase64String(filename, value string) (*os.File, error) {
f, err := os.Create(filename)
if err != nil {
fmt.Println("mongodb.initFileFromBase64String - err: ", err)
return nil, err
}
b := base64DecodeToBytes(value)
if _, err := f.Write(b); err != nil {
fmt.Println("mongodb.initFileFromBase64String - write file err: ", err)
return nil, err
}
f.Sync()
return f, nil
}