如何为 Go 服务器应用程序设置 Let's Encrypt
时间:2023-04-15
浏览:349
作者:佚名
大家好,我们又见面了啊~本文《如何为 Go 服务器应用程序设置 Let's Encrypt》的内容中将会涉及到golang等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~
问题内容
我有自己的域,其中包含用 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,
},
}
go http.ListenAndServe(":http", certManager.HTTPHandler(nil))
log.Fatal(server.ListenAndServeTLS("", "")) //Key and cert are coming from Let's Encrypt
}
关于 autocert 包的更多信息:链接
[编辑:由于letsencrypt安全问题](https://community.letsencrypt.org/t/important-what-you- need-to-know-about-tls-sni-validation- issues/50811)需要使http可用,在这里阅读更多。作为此修复的奖励,我们现在有 http-->https 重定向。如果您已经收到证书,旧示例将继续工作,但它会因新站点而中断。
终于介绍完啦!小伙伴们,这篇关于《如何为 Go 服务器应用程序设置 Let's Encrypt》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
