Golang crypto/tls.Conn type and inner functions examples

package crypto/tls

A Conn represents a secured connection. It implements the net.Conn interface.

func (*Conn) Close usage example

 config := tls.Config{ RootCAs: roots, ServerName: "mail.google.com", InsecureSkipVerify:true,}
 config.Rand = rand.Reader
 config.BuildNameToCertificate()

 conn, err := tls.Dial("tcp", "mail.google.com:443", &config)
 if err != nil {
 panic("failed to connect: " + err.Error())
 }
 conn.Close()

func (*Conn) ConnectionState usage example

 // populate tls.Config with dummy data
 tlsConn := tls.Server(conn, &tls.Config{
 RootCAs: roots,ServerName : "mail.google.com", InsecureSkipVerify: true,
 })

 // skip Handshake ... not with google mail server
 connstate := tlsConn.ConnectionState()

func (*Conn) Handshake usage example

 // Note : tlsConn.Read and tlsConn.Write functions will automatically
 // initiate handshake protocol if not called
 err = tlsConn.Handshake()

func (*Conn) LocalAddr usage example

 fmt.Printf("Local Address : %s\n", tlsConn.LocalAddr().String())

func (*Conn) OCSPResponse usage example

 fmt.Printf("OCSPResponse : %v\n", tlsConn.OCSPResponse())

func (*Conn) Read usage example

 buffer := make([]byte, 1)

 if _, err := tlsConn.Read(buffer); err != nil {
 if err != io.EOF {
 fmt.Printf("Failed to read byte: %s\n", err)
 }
 }

func (*Conn) RemoteAddr usage example

 fmt.Printf("Remote Address : %s\n", tlsConn.RemoteAddr().String())

func (*Conn) SetDeadline usage example

 // applicable to BOTH tls.Read and tls.Write functions
 err = tlsConn.SetDeadline(time.Now().Add(500 * time.Millisecond))

 if err != nil {
 fmt.Println("Failed to set dead line for tls.Read and tls.Write", err)
 }

func (*Conn) SetReadDeadline usage example

 // only applicable to tls.Read function
 err = tlsConn.SetReadDeadline(time.Now().Add(500 * time.Millisecond))

 if err != nil {
 fmt.Println("Failed to set dead line for tls.Read", err)
 }

func (*Conn) SetWriteDeadline usage example

 // applicable to tls.Write function
 err = tlsConn.SetWriteDeadline(time.Now().Add(500 * time.Millisecond))

 if err != nil {
 fmt.Println("Failed to set dead line for tls.Write", err)
 }

func (*Conn) VerifyHostname usage example

 err = tlsConn.VerifyHostname("localhost")  // or tslConn.VerifyHostname(config.ServerName)  ... read the official documentation ;-)

 if err != nil {
 fmt.Println(err)
 }

func (*Conn) Write usage example

 if _, err := tlsConn.Write([]byte("Hello World!\n")); err != nil {
 fmt.Printf("Failed to write byte : %s\n", err)
 }

Advertisement