在Ubuntu上为Golang应用程序配置SSL,你需要遵循以下步骤:
sudo apt update
sudo apt install certbot
yourdomain.com替换为你的实际域名:sudo certbot certonly --standalone -d yourdomain.com
Certbot会检查你的域名是否已经配置了DNS,并在成功验证后为你生成SSL证书。证书文件通常位于/etc/letsencrypt/live/yourdomain.com/目录下。
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, SSL!")
})
certFile := "/etc/letsencrypt/live/yourdomain.com/fullchain.pem"
keyFile := "/etc/letsencrypt/live/yourdomain.com/privkey.pem"
log.Printf("Starting HTTPS server on :443")
err := http.ListenAndServeTLS(":443", certFile, keyFile, nil)
if err != nil {
log.Fatal(err)
}
}
在这个示例中,我们使用了ListenAndServeTLS函数来启动一个HTTPS服务器,并提供了证书文件和密钥文件的路径。
重新加载Golang应用程序: 保存你的更改并重新加载Golang应用程序。现在,你的应用程序应该可以通过HTTPS访问了。
设置自动更新证书:
Let’s Encrypt证书有效期为90天。为了确保证书始终有效,你需要设置自动更新。Certbot提供了一个名为certbot renew的命令来更新证书。你可以将此命令添加到cron作业中,以便在证书到期前自动更新。
运行以下命令以编辑cron作业:
sudo crontab -e
在打开的编辑器中,添加以下行以每天检查并更新证书:
0 0 * * * certbot renew --post-hook "systemctl reload your-golang-app.service"
将your-golang-app.service替换为你的Golang应用程序的实际systemd服务名称。保存并关闭编辑器。
现在,你的Golang应用程序应该在Ubuntu上使用SSL运行,并且证书将自动更新。