Skip to content

Instantly share code, notes, and snippets.

@choestelus
Created April 25, 2018 11:52
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save choestelus/8ddcc7106cc247cb5129d4e9c8ba5d64 to your computer and use it in GitHub Desktop.
Save choestelus/8ddcc7106cc247cb5129d4e9c8ba5d64 to your computer and use it in GitHub Desktop.
go-pg with TLS connection example
package main
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"github.com/go-pg/pg"
log "github.com/sirupsen/logrus"
)
func main() {
cert, err := tls.LoadX509KeyPair("postgresql.crt", "postgresql.key")
if err != nil {
log.Errorf("failed to load client certificate: %v", err)
}
CAFile := "root.crt"
CACert, err := ioutil.ReadFile(CAFile)
if err != nil {
log.Errorf("failed to load server certificate: %v", err)
}
CACertPool := x509.NewCertPool()
CACertPool.AppendCertsFromPEM(CACert)
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert},
RootCAs: CACertPool,
InsecureSkipVerify: true,
// ServerName: "localhost",
}
opt := &pg.Options{
Addr: "localhost:5432",
Database: "postgres",
User: "postgres",
TLSConfig: tlsConfig,
}
DB := pg.Connect(opt)
var num int
_, err = DB.QueryOne(pg.Scan(&num), `SELECT 1+1`)
if err != nil {
log.Errorf("failed to query db: %v", err)
}
log.Infof("DB string: %v", DB.String())
fmt.Printf("query resp : %v\n", num)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment