猿问

如何为 Go 服务器应用程序设置 Let's Encrypt

我有自己的域,其中包含用 Go 编写的 Web 服务。我使用的是内置的 Go Web 服务器,前面没有 Nginx 或 Apache。

我想开始通过 HTTPS 提供服务,我意识到 Let's Encrypt 即将成为这样做的方式。

任何人都可以分享配置在 Linux 服务器上运行的 Go 应用程序的整个设置过程吗?


蝴蝶刀刀
浏览 191回答 3
3回答

当年话下

这是使用我发现的 Go 和 Let's Encrypt 证书的 HTTPS 服务器的最小自动设置:package mainimport (    "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安全问题需要使http可用,在这里阅读更多。作为此修复的奖励,我们现在有 http-->https 重定向。如果您已经收到证书,旧示例将继续工作,但它会因新站点而中断。

月关宝盒

我找到了一个非常简单的解决方案,使用独立模式。安装 CERTBOT 客户端(由 Let's Encrypt 推荐)(go to the directory where you want to install the certbot client)git clone https://github.com/certbot/certbotcd certbot./certbot-auto --help`签发证书(第一次)注意此操作通过端口 80 发生,因此如果您的 Go 应用程序侦听端口 80,则需要在运行此命令之前将其关闭(顺便说一下,运行速度非常快)./certbot-auto certonly --standalone-supported-challenges http-01 -d www.yourdomain.com在您的 GO 代码中添加 SSL 侦听器http.ListenAndServeTLS(":443", "/etc/letsencrypt/live/www.yourdomain.com/fullchain.pem", "/etc/letsencrypt/live/www.yourdomain.com/privkey.pem", nil)完毕!更新证书(证书在 90 天后过期)注意您可以手动运行此程序(您将在证书到期前几天收到一封电子邮件),或者设置一个 crontab如果您的 Go 应用程序不再监听端口 80,您的 Go 应用程序可以在您执行以下命令时继续运行:./certbot-auto renew --standalone如果您的 Go 应用程序仍在侦听端口 80,您可以指定停止和重新启动 Go 应用程序的命令:./certbot-auto renew --standalone --pre-hook "command to stop Go app" --post-hook "command to start Go app"有关 Certbot 命令的完整文档:https ://certbot.eff.org/docs/using.html

大话西游666

如果您可以使用 DNS 验证,那就是续订的方法。要使用证书,只需执行以下操作:    c := &tls.Config{MinVersion: tls.VersionTLS12}    s := &http.Server{Addr: ":443", Handler: Gzipler(nosurf.New(router), 1), TLSConfig: c}    log.Fatal(s.ListenAndServeTLS(        "/etc/letsencrypt/live/XXX/fullchain.pem",         "/etc/letsencrypt/live/XXX/privkey.pem"    ))这个包含 Gzip 和 CSRF 保护。您可以使用Handler: router没有那些额外的功能。
随时随地看视频慕课网APP

相关分类

Go
我要回答