Skip to content

Instantly share code, notes, and snippets.

@adamcfraser
Last active May 1, 2018 16:16
Show Gist options
  • Save adamcfraser/8c5a6c21c34252d98623fad003757be5 to your computer and use it in GitHub Desktop.
Save adamcfraser/8c5a6c21c34252d98623fad003757be5 to your computer and use it in GitHub Desktop.
// Connect to a memcached server.
func Connect(prot, dest string) (rv *Client, err error) {
conn, err := dialFun(prot, dest)
if err != nil {
return nil, err
}
tcpConn, isTcpConn := conn.(*net.TCPConn)
if !isTcpConn {
log.Printf("Not TCP Conn: %T", conn)
return Wrap(conn)
} else {
err = tcpConn.SetNoDelay(false)
if err != nil {
log.Printf("Failed to disable TCP nodelay (%s)", err)
}
tlsConfig, configErr := McClientConfigForX509("/Users/adam/Desktop/x509/chain.pem",
"/Users/adam/Desktop/x509/pkey.key", "/Users/adam/Desktop/x509/ca.pem")
if configErr != nil {
log.Printf("error building tls config: %v", configErr)
}
tlsConfig.ServerName = "127.0.0.1"
log.Printf("MC tlsConfig: %+v", tlsConfig)
tlsConn := tls.Client(tcpConn, tlsConfig)
tlsErr := tlsConn.Handshake()
if tlsErr != nil {
log.Printf("tls handshake failed with error: %v", tlsErr)
}
return Wrap(tlsConn)
}
}
func McClientConfigForX509(certFile, keyFile, rootFile string) (*tls.Config, error) {
cfg := &tls.Config{}
if certFile != "" && keyFile != "" {
tlsCert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, err
}
cfg.Certificates = []tls.Certificate{tlsCert}
} else {
//error need to pass both certfile and keyfile
return nil, fmt.Errorf("N1QL: Need to pass both certfile and keyfile")
}
var caCert []byte
var err1 error
caCertPool := x509.NewCertPool()
if rootFile != "" {
// Read that value in
caCert, err1 = ioutil.ReadFile(rootFile)
if err1 != nil {
return nil, fmt.Errorf(" Error in reading cacert file, err: %v", err1)
}
caCertPool.AppendCertsFromPEM(caCert)
}
cfg.RootCAs = caCertPool
return cfg, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment