Serving content over HTTPS in golang
Serving HTTPS content with golang is pretty straight forward. You’ll need to your certificate/key pem files to ListenAndServeTLS but that’s about it. However you may also want to insure that your users always use HTTPS in which case you can also listen on port 80 and just redirect them to the HTTPS site using RedirectHandler. The example below shows how you might do this:
package main import ( "net/http" "net" ) func main() { http.Handle("/", http.FileServer(http.Dir("."))) go func() { err := http.ListenAndServe(":80", http.RedirectHandler("https://mywebsite.com", http.StatusFound)) if err != nil { panic("Error: " + err.Error()) } }() err := http.ListenAndServeTLS(":443", "cert.pem", "key.pem", nil) if err != nil { panic("Error: " + err.Error()) } }