-
-
Save fabdelgado/0ba7d29fbed2be43d0a25700f4489ed0 to your computer and use it in GitHub Desktop.
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
package mysql | |
import ( | |
"crypto/tls" | |
"crypto/x509" | |
"fmt" | |
_ "github.com/go-sql-driver/mysql" | |
"gorm.io/driver/mysql" | |
"gorm.io/gorm" | |
"io" | |
"log" | |
"os" | |
) | |
var Db *gorm.DB | |
// InitDatabase initialize db connection | |
func InitDatabase() *gorm.DB { | |
var err error | |
dbHost := os.Getenv("DB_HOST") | |
dbPort := os.Getenv("DB_PORT") | |
dbName := os.Getenv("DB_NAME") | |
dbUser := os.Getenv("DB_USER") | |
dbPass := os.Getenv("DB_PASS") | |
dbTls := os.Getenv("DB_TLS") | |
parseTime := os.Getenv("DB_PARSETIME") | |
//Read certificate | |
file, err := os.Open("./ca.pem") | |
if err != nil { | |
log.Fatalf("Failed to read file %s", file) | |
} | |
//Setup certificate for mysql | |
rootCertPool := x509.NewCertPool() | |
// read pem file | |
pem, err := io.ReadAll(file) | |
if err != nil { | |
log.Fatalf("Failed to read: %s", err.Error()) | |
} | |
// append pem file for connection | |
if ok := rootCertPool.AppendCertsFromPEM(pem); !ok { | |
log.Fatalf("Failed to append root ca.pem") | |
} | |
mysql.RegisterTLSConfig("custom", &tls.Config{ | |
RootCAs: rootCertPool, | |
InsecureSkipVerify: true, | |
}) | |
// make a connection string | |
connStr := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?tls=%s&parseTime=%s", dbUser, dbPass, dbHost, dbPort, dbName, | |
dbTls, parseTime) | |
// connect to database | |
Db, err = gorm.Open("mysql", connStr) | |
if err != nil { | |
fmt.Println(err.Error()) | |
//return err | |
} | |
return Db | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment