在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應用程序?,F在,你的應用程序應該可以通過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運行,并且證書將自動更新。