为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
蝴蝶刀刀 2022-01-10 17:21:20
我有自己的域,其中包含用 Go 编写的 Web 服务。我使用的是内置的 Go Web 服务器,前面没有 Nginx 或 Apache。我想开始通过 HTTPS 提供服务,我意识到 Let's Encrypt 即将成为这样做的方式。任何人都可以分享配置在 Linux 服务器上运行的 Go 应用程序的整个设置过程吗?
查看完整描述

3 回答

?
当年话下

TA贡献1890条经验 获得超9个赞

这是使用我发现的 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安全问题需要使http可用,在这里阅读更多。作为此修复的奖励,我们现在有 http-->https 重定向。如果您已经收到证书,旧示例将继续工作,但它会因新站点而中断。


查看完整回答
反对 回复 2022-01-10
?
月关宝盒

TA贡献1772条经验 获得超5个赞

我找到了一个非常简单的解决方案,使用独立模式。



安装 CERTBOT 客户端(由 Let's Encrypt 推荐)


(go to the directory where you want to install the certbot client)

git clone https://github.com/certbot/certbot

cd 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


查看完整回答
反对 回复 2022-01-10
?
大话西游666

TA贡献1817条经验 获得超14个赞

如果您可以使用 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

没有那些额外的功能。


查看完整回答
反对 回复 2022-01-10
  • 3 回答
  • 0 关注
  • 190 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信