How to create an HTTPS server with SSL/TLS certificate handling in Go?

To create an HTTPS server with SSL/TLS certificate handling in Go, you can follow these steps:

  1. Generate SSL/TLS certificates:

    • You can use a tool like OpenSSL to create a self-signed certificate or obtain a certificate from a Certificate Authority (CA).
  2. Prepare your server code:

package main import ( "crypto/tls" "log" "net/http" ) func main() { // Load the SSL/TLS certificate and private key cert, err := tls.LoadX509KeyPair("path/to/cert.pem", "path/to/key.pem") if err != nil { log.Fatal(err) } // Create a new HTTPS server using the certificate and private key server := &http.Server{ Addr: ":8443", TLSConfig: &tls.Config{ Certificates: []tls.Certificate{cert}, }, } // Define your handler function http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello, HTTPS!")) }) // Start the HTTPS server err = server.ListenAndServeTLS("", "") if err != nil { log.Fatal(err) } }
  1. Replace "path/to/cert.pem" and "path/to/key.pem" with the actual paths to your SSL/TLS certificate and private key files.

  2. In the server.ListenAndServeTLS("", "") line, the first empty string indicates that the server should listen on all network interfaces, and the second empty string means that Go should use the default server TLS configuration.

  3. Save the code in a file, such as main.go, and run it using go run main.go.

Now you have a simple HTTPS server running in Go with SSL/TLS certificate handling. You can access the server using https://localhost:8443 in your browser. Keep in mind that as it is a self-signed certificate, the browser may show a security warning. For production use, obtain a proper SSL/TLS certificate from a trusted CA.