Golang : Secure(TLS) connection between server and client
This is additional tutorial for the previous tutorial on creating simple client-server program with Golang. In this tutorial, we will learn how to established secure(TLS - Transport Layer Security) connection between a server and client.
Before executing the code below, please generate 2 sets of certificates - one set for server and one set for client.
To keep this tutorial simple, we will use these commands :
>openssl req -new -nodes -x509 -out server.pem -keyout server.key -days 365
>openssl req -new -nodes -x509 -out client.pem -keyout client.key -days 365
just leave everything to the default value by pressing enter until the end.
Execute the server.go program below as a background process. Modify the port number or IP address to fit your own requirement.
server.go
package main
import (
"crypto/rand"
"crypto/tls"
"fmt"
"log"
"net"
)
func handleConnection(c net.Conn) {
log.Printf("Client(TLS) %v connected via secure channel.", c.RemoteAddr())
// stuff to do... like read data from client, process it, write back to client
// see what you can do with (c net.Conn) at
// http://golang.org/pkg/net/#Conn
// buffer := make([]byte, 4096)
//for {
// n, err := c.Read(buffer)
// if err != nil || n == 0 {
// c.Close()
// break
// }
// n, err = c.Write(buffer[0:n])
// if err != nil {
// c.Close()
// break
// }
// }
log.Printf("Connection from %v closed.", c.RemoteAddr())
}
func main() {
cert, err := tls.LoadX509KeyPair("server.pem", "server.key")
if err != nil {
log.Fatal(err)
}
config := tls.Config{Certificates: []tls.Certificate{cert}, ClientAuth: tls.RequireAnyClientCert
}
config.Rand = rand.Reader
ln, err := tls.Listen("tcp", ":6600", &config)
if err != nil {
log.Fatal(err)
}
fmt.Println("Server(TLS) up and listening on port 6600")
for {
conn, err := ln.Accept()
if err != nil {
log.Println(err)
continue
}
go handleConnection(conn)
}
}
and on a separate machine. Run the client.go program
client.go
package main
import (
"crypto/tls"
"log"
)
func main() {
cert, err := tls.LoadX509KeyPair("client.pem", "client.key")
if err != nil {
log.Fatal(err)
}
hostName := "example.com" // change this
portNum := "6600"
log.Printf("Connecting to %s\n", hostName)
config := tls.Config{Certificates: []tls.Certificate{cert}, InsecureSkipVerify: true}
conn, err := tls.Dial("tcp", hostName+":"+portNum, &config)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
log.Printf("Connection established between %s and localhost.\n", conn.RemoteAddr().String())
log.Println("Bye...")
}
Sample output :
./client-dial-tls
2015/05/09 22:04:58 Connecting to socketloop.com
./server
Server(TLS) up and listening on port 6600
2015/05/09 10:04:59 Client(TLS) 14.192.213.197:2547 connected via secure channel.
2015/05/09 10:04:59 Connection from 14.192.213.197:2547 closed.
One of the few things that you might want to add to this tutorial is to send data from client to server and get the server to echo back to the client. I leave this to you as exercise ;-)
References :
http://en.wikipedia.org/wiki/TransportLayerSecurity
https://www.socketloop.com/tutorials/golang-simple-client-server-example
See also : Golang : Simple client server example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+9.5k Golang : Sort and reverse sort a slice of floats
+9.1k Golang : How to get username from email address
+39.3k Golang : Remove dashes(or any character) from string
+10.7k Nginx : TLS 1.2 support
+6.5k Golang : Output or print out JSON stream/encoded data
+5.7k Golang : List all packages and search for certain package
+4.1k Golang : Converting individual Jawi alphabet to Rumi(Romanized) alphabet example
+17.4k Golang : Defer function inside init()
+6.2k PHP : Proper way to get UTF-8 character or string length
+17.5k Golang : Iterate linked list example
+10.3k Golang : Allow Cross-Origin Resource Sharing request
+5.5k Fix fatal error: evacuation not done in time problem