drsxzut183207938 2018-09-18 21:18
浏览 127
已采纳

如何通过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!

  • 写回答

1条回答 默认 最新

  • dousi9215 2018-09-18 21:44
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用