How to set up HTTPS on golang web server?
You need http.ListenAndServeTLS
package main
import (
// "fmt"
// "io"
"net/http"
"log"
)
func HelloServer(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("This is an example server.\n"))
// fmt.Fprintf(w, "This is an example server.\n")
// io.WriteString(w, "This is an example server.\n")
}
func main() {
http.HandleFunc("/hello", HelloServer)
err := http.ListenAndServeTLS(":443", "server.crt", "server.key", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
Here’s a snippet: https://gist.github.com/denji/12b3a568f092ab951456
Use https://golang.org/pkg/net/http/#ListenAndServeTLS
http.HandleFunc("/", handler)
log.Printf("About to listen on 10443. Go to https://127.0.0.1:10443/")
err := http.ListenAndServeTLS(":10443", "full-cert.crt", "private-key.key", nil)
log.Fatal(err)
For Go you need one certificate file (containing one or more certs, starting with yours) and one private key file (containing one private key).
This isn't really a go question, but the intermediate certs are required because computers only store root certs. By concatenating them you put them all in one file so the browser gets all certs - this is a required step otherwise your server will fail on certain devices. Your cert provider will provide instructions for doing this.
https://kb.wisc.edu/page.php?id=18923
To combine the certs you can just use cat (making sure they have a line feed at the end of the file first), something like:
cat example.com.ca-crt example.com.ca-bundle > example.com.crt