亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何通過 HTTPS 提供靜態文件

如何通過 HTTPS 提供靜態文件

Go
慕尼黑8549860 2023-04-04 17:07:41
我一直在為這個問題撓頭太久——我的問題相當微不足道,但我自己真的弄不明白:如何在 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"))}任何幫助表示贊賞,謝謝!
查看完整描述

1 回答

?
慕神8447489

TA貢獻1780條經驗 獲得超1個贊

您需要使用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創建自簽名證書進行測試。


查看完整回答
反對 回復 2023-04-04
  • 1 回答
  • 0 關注
  • 146 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號