go語言使用gin網頁框架加上Let's Encrypt的https憑證簡單範例

這週學一點go語言在嘗試拿來架站,沒想到已經可以很快的應用上Let's  Encrypt的https憑證

直接上程式碼 https.go

package main

import (
"log"
"net/http"

"github.com/gin-gonic/gin"
"golang.org/x/crypto/acme/autocert"
)

func main() {
gin.SetMode(gin.ReleaseMode)

r := gin.Default()

r.GET("/ping", func(c *gin.Context) {
c.String(200, "pong")
})

log.Fatal(http.Serve(autocert.NewListener("your-domain.com"), r))
}

這段程式碼的意思:

  1. 將gin設為release模式
  2. 生成預設的gin路由
  3. 加入一個get路由,路徑是/ping, 把http code 200和字串"pong"丟給client
  4. 指定autocert幫忙處理"your-domain.com"的憑證,再將設定好的路由一併交給http.Serve啟動服務,如果有錯誤就印出來並結束程式

程式碼裡頭的"your-domain.com"需要你自己註冊的domain,你還需要一台VPS主機

  • 我是用google domain購買註冊安全的.page網域,年費是台幣290+稅+2%海外交易信用卡交易費
  • 然後在google domain裡頭設定dns,加入類型A(針對IPv4)或者AAAA(針對IPv6)到你的VPS

然後再編譯這隻go程式

我本機跟遠端都是ubuntu 22.04所以就只需要build就可以把執行檔放上去

go mod init https

go mod tidy

go build

生成的執行檔是https,上傳到你的遠端主機

scp https {your-domain}:{放置路徑}

設定程式可以綁定埠號

sudo setcap CAP_NET_BIND_SERVICE+ep https

設定防火牆開啟https的埠

sudo ufw allow https

執行程式

./https

參考:

https://blog.wu-boy.com/2017/04/1-line-letsencrypt-https-servers-in-golang/

留言