Introduction

In today's internet-driven world, ensuring secure communication via web servers is critical. In this guide, we'll focus on securing HTTP servers written in the Go programming language by utilizing HTTPS and certificates.

Prerequisites

  • Basic understanding of Go programming language
  • Go environment setup on your machine

Setting Up an HTTP Server in Go

Before we dive into HTTPS, let's set up a basic HTTP server using Go. This will be our starting point.


package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, this is an HTTP server!")
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

With this simple code snippet, you've initiated an HTTP server running on port 8080.

Moving from HTTP to HTTPS

To secure our server with HTTPS, we need to perform a few additional steps, including obtaining a TLS certificate.

Generating a Self-signed TLS Certificate

For development or testing purposes, you might choose to generate a self-signed certificate. Be aware that self-signed certificates are not trusted by default browsers and must be used cautively.


$ openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout server.key -out server.crt

Running the above command will produce a server.key (private key) and server.crt (certificate) for use in your server configuration.

Integrating HTTPS into the Go Server

Next, let's modify our server code to utilize HTTPS with the TLS certificate.


package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, this is an HTTPS server!")
}

func main() {
    http.HandleFunc("/", handler)
    err := http.ListenAndServeTLS(":443", "server.crt", "server.key", nil)
    if err != nil {
        fmt.Println("Error starting server:", err)
        return
    }
}

This modification uses the http.ListenAndServeTLS function, which listens for HTTPS connections on port 443 by default, utilizing our self-signed certificate.

Conclusion

You've successfully converted a basic HTTP server into a secure HTTPS server in Go using self-signed certificates. In production environments, always acquire certificates from certificate authorities to ensure that your server is trusted by clients.