Secure TCP connections in Go by wrapping the net.Conn with tls.Client or tls.Server and performing a handshake.
Wrap your TCP connection with tls.Client or tls.Server using a tls.Config to enable encryption.
import (
"crypto/tls"
"net"
)
conn, err := net.Dial("tcp", "example.com:443")
if err != nil {
// handle error
}
config := &tls.Config{
ServerName: "example.com",
}
tlsConn := tls.Client(conn, config)
if err := tlsConn.Handshake(); err != nil {
// handle error
}
// Use tlsConn for secure read/write
TLS acts like a secure tunnel for your data, scrambling it so only the intended recipient can read it. You use it whenever you need to send sensitive information over the internet, like passwords or credit card numbers. Think of it as putting your letter in a locked steel box before mailing it instead of a plain envelope.