gohttpsstatic-content

How to serve static files over HTTPS


I have been scratching my head for way too long with this one - my issue is rather trivial however I cannot really figure it out myself: how does one serve static files over HTTPS in Go?

So far I have tried using both HTTP.ServeFile and mux.Handle with no particular success whatsoever.

func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
    w.Header().Add("Strict-Transport-Security", "max-age=63072000; includeSubDomains")
    http.ServeFile(w, req, "./static")
})

cfg := &tls.Config{
    MinVersion:               tls.VersionTLS12,
    CurvePreferences:         []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},
    PreferServerCipherSuites: true,
    CipherSuites: []uint16{
        tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
        tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
        tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
        tls.TLS_RSA_WITH_AES_256_CBC_SHA,
    },
}
srv := &http.Server{
    Addr:         ":8080",
    Handler:      mux,
    TLSConfig:    cfg,
    TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler), 0),
}
log.Fatal(srv.ListenAndServeTLS("./server.rsa.crt", "./server.rsa.key"))

}

Any help is appreciated, thanks!


Solution

  • You need to use http.ListenAndServeTLS to start an HTTPS server.

    func main() {
        // Set up the handler to serve a file
        http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
            w.Header().Set("Content-Type", "text/plain; charset=utf-8")
            http.ServeFile(w, req, "./text.txt")
        })
    
        log.Printf("About to listen on 8443. Go to https://127.0.0.1:8443/")
        log.Fatal(http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", nil))
    }
    

    And to start an HTTPS server serving a directory with FileServer...

    log.Fatal(http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", http.FileServer(http.Dir("./static"))))
    

    You can use generate_cert.go to create self-signed certificates for testing.