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
+4.9k JavaScript/JQuery : Redirect page examples
+5.9k Golang & Javascript : How to save cropped image to file on server
+7.2k Golang : Rename part of filename
+15.1k Golang : Get digits from integer before and after given position example
+11k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions
+18.4k Golang : convert int to string
+5.9k Golang : How to search a list of records or data structures
+5.3k Golang : Detect words using using consecutive letters in a given string
+35.3k Golang : Get file last modified date and time
+13.8k Golang : How to pass map to html template and access the map's elements
+34.5k Golang : Upload and download file to/from AWS S3
+11.8k Golang : convert(cast) string to integer value