我有自己的域,其中包含用 Go 编写的 Web 服务。我使用内置的 Go Web 服务器,前面没有 Nginx 或 Apache。
我想开始通过 HTTPS 提供服务,并且我意识到 Let's Encrypt 即将成为实现这一目标的方法。
谁能分享配置在 Linux 服务器上运行的 Go 应用程序的整个设置过程?
这是我发现的使用 Go 和 Let's Encrypt 证书的 HTTPS 服务器的最小自动设置:
package main
import (
"crypto/tls"
"log"
"net/http"
"golang.org/x/crypto/acme/autocert"
)
func main() {
certManager := autocert.Manager{
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist("example.com"), //Your domain here
Cache: autocert.DirCache("certs"), //Folder for storing certificates
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello world"))
})
server := &http.Server{
Addr: ":https",
TLSConfig: &tls.Config{
GetCertificate: certManager.GetCertificate,
MinVersion: tls.VersionTLS12, // improves cert reputation score at https://www.ssllabs.com/ssltest/
},
}
go http.ListenAndServe(":http", certManager.HTTPHandler(nil))
log.Fatal(server.ListenAndServeTLS("", "")) //Key and cert are coming from Let's Encrypt
}
有关 autocert 包的更多信息:link https://godoc.org/golang.org/x/crypto/acme/autocert
编辑:需要使 http 可用,因为LetsEncrypt安全问题 https://community.letsencrypt.org/t/important-what-you-need-to-know-about-tls-sni-validation-issues/50811, 阅读更多here https://github.com/golang/go/issues/21890。作为此修复的额外好处,我们现在有了 http-->https 重定向。如果您已经收到了证书,旧示例将继续工作,但对于新站点来说它将中断。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)