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 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私