【问题标题】:How to serve static files over HTTPS如何通过 HTTPS 提供静态文件
【发布时间】:2019-02-22 23:18:00
【问题描述】:

我一直在为这个问题挠头太久了——我的问题相当琐碎,但我自己无法真正弄清楚:如何在 Go 中通过 HTTPS 提供静态文件?

到目前为止,我已经尝试同时使用HTTP.ServeFilemux.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"))

}

感谢任何帮助,谢谢!

【问题讨论】:

  • 你需要创建一个https服务器。您使用的是http.ListenAndServeTLS 而不是http.ListenAndServe 吗?

标签: go https static-content


【解决方案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 创建自签名证书进行测试。

【讨论】:

  • 不一定是我想要的,我已经用更长的代码更新了这个问题。问题是我正在使用我的自定义多路复用器,除了 cert.pem 和 key.pem 之外,不能向 ListenAndServeTLS 方法抛出任何其他参数。
  • @Maciej21592 如果我将"./static" 更改为存在的文件,您的代码对我有用。你有什么问题?是不是因为./static是目录,不是文件?
  • 是的,它确实是一个包含多个 javascript/css 文件的目录。
  • @Maciej21592 你从服务器得到一个 404?这是因为ServeFile 提供单个文件。
  • 我已经设法解决了这个问题; fs := http.FileServer(http.Dir("static")) mux.Handle("/static/", http.StripPrefix("/static/", fs)) ...问题是文件服务器仍然使用 HTTP 1.1 而不是 HTTPS 为我提供静态资源 :(
猜你喜欢
  • 2011-10-20
  • 1970-01-01
  • 2014-05-17
  • 1970-01-01
  • 2011-01-16
  • 2015-03-18
  • 1970-01-01
  • 2017-03-23
  • 2013-09-18
相关资源
最近更新 更多