go - 如何通过 HTTPS 提供静态文件

标签 go https static-content

我已经为这个问题挠头太久了——我的问题相当微不足道,但我自己也搞不清楚:如何在 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"))

}

感谢任何帮助,谢谢!

最佳答案

您需要使用 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创建用于测试的自签名证书。

关于go - 如何通过 HTTPS 提供静态文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52394720/

相关文章:

go - 在 go 中输入断言

arrays - 排列数组类型的映射键并 slice 每个数组会为每次迭代提供相同的数组

ssl - 从 Web App 调用 Web API 时出现证书问题

java - 如何从 Grails 中的 Http 响应获取 boolean 值

python - 带 zappa 的白噪声,将静态文件推送到 s3?

apache - 使用 Apache 和 mod_proxy_ajp 提供静态 Jenkins 内容

grails - 从Grails应用程序中的应用程序服务器外部提供静态数据的最简单方法

go - Go 语言中的副作用

go - 从go例程中堆叠数据

node.js - 如何使用node正确创建HTTPS透明代理服务器?