这个问题我已经花了太长时间了-我的问题相当琐碎,但是我自己却无法弄清楚:如何在Go中通过HTTPS提供静态文件?
到目前为止,我已经尝试同时使用HTTP.ServeFile
和mux.Handle
,但没有任何成功。
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"))
}
感谢您的帮助,谢谢!
答案 0 :(得分:0)
您需要使用http.ListenAndServeTLS来启动HTTPS服务器。
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))
}
然后启动一个HTTPS服务器,该服务器使用FileServer
...
log.Fatal(http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", http.FileServer(http.Dir("./static"))))
您可以使用generate_cert.go
创建用于测试的自签名证书。