Created
April 25, 2018 11:52
-
-
Save choestelus/8ddcc7106cc247cb5129d4e9c8ba5d64 to your computer and use it in GitHub Desktop.
go-pg with 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
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