Created
March 12, 2024 18:48
-
-
Save cloakd/84b8425a2277fa4eb3473a357262dace to your computer and use it in GitHub Desktop.
Postgres Gorm TLS Connection example
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
type PostgresService struct { | |
db *gorm.DB | |
username string | |
password string | |
database string | |
host string | |
port string | |
} | |
const POSTGRES_SVC = "postgres_svc" | |
// Id returns Service ID | |
func (ds PostgresService) Id() string { | |
return POSTGRES_SVC | |
} | |
// Db Access to raw SqliteService db | |
func (ds PostgresService) Db() *gorm.DB { | |
return ds.db | |
} | |
// Configure the service | |
func (ds *PostgresService) Configure(ctx *context.Context) error { | |
ds.username = os.Getenv("DB_USERNAME") | |
ds.password = os.Getenv("DB_PASSWORD") | |
ds.host = os.Getenv("DB_HOST") | |
ds.port = os.Getenv("DB_PORT") | |
ds.database = os.Getenv("DB_DATABASE") | |
return ds.DefaultService.Configure(ctx) | |
} | |
// Start the service and open connection to the database | |
// Migrate any tables that have changed since last runtime | |
func (ds *PostgresService) Start() (err error) { | |
var logLevel logger.LogLevel | |
if os.Getenv("DEBUG") != "" { | |
logLevel = logger.Error | |
} else { | |
logLevel = logger.Silent | |
} | |
// Load CA Cert | |
rootCertPool := x509.NewCertPool() | |
pem, err := os.ReadFile("./postgres.crt") | |
if err != nil { | |
return err | |
} | |
if ok := rootCertPool.AppendCertsFromPEM(pem); !ok { | |
return errors.New("failed to append pem") | |
} | |
stdlib.RegisterConnConfig(&pgx.ConnConfig{ | |
Config: pgconn.Config{ | |
TLSConfig: &tls.Config{RootCAs: rootCertPool}, | |
}, | |
}) | |
ds.db, err = gorm.Open(postgres.New(postgres.Config{ | |
DSN: fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%v sslmode=require TimeZone=UTC", ds.host, ds.username, ds.password, ds.database, ds.port), | |
}), &gorm.Config{ | |
Logger: logger.Default.LogMode(logLevel), | |
PrepareStmt: true, | |
}) | |
return err | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment