安裝
使用 go get 安裝 Go QR碼函式庫。
go get
go get github.com/skip2/go-qrcode使用 Go 產生 QR碼
使用 go-qrcode 函式庫的程式碼範例。
Basic QR Code Generation
package main
import "github.com/skip2/go-qrcode"
func main() {
err := qrcode.WriteFile("https://qrcode.fun", qrcode.Medium, 256, "qrcode.png")
if err != nil {
panic(err)
}
}QR Code as Bytes (HTTP Handler)
package main
import (
"net/http"
"github.com/skip2/go-qrcode"
)
func qrHandler(w http.ResponseWriter, r *http.Request) {
data := r.URL.Query().Get("data")
if data == "" {
data = "https://qrcode.fun"
}
png, err := qrcode.Encode(data, qrcode.Medium, 256)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
w.Header().Set("Content-Type", "image/png")
w.Write(png)
}
func main() {
http.HandleFunc("/qr", qrHandler)
http.ListenAndServe(":8080", nil)
}QRCode.fun API
透過 API 在 Go 中產生 QR碼
從 Go 呼叫 QRCode.fun API 產生樣式化 QR碼。
Go API 整合
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
func main() {
payload := map[string]interface{}{
"data": "https://qrcode.fun",
"width": 300,
"height": 300,
"type": "png",
"margin": 10,
"dotsOptions": map[string]string{
"color": "#1A2B3C",
"type": "rounded",
},
"cornersSquareOptions": map[string]string{
"color": "#8564C3",
"type": "extra-rounded",
},
"backgroundOptions": map[string]string{
"color": "#FFFFFF",
},
}
body, _ := json.Marshal(payload)
resp, err := http.Post(
"https://qrcode.fun/api/generate-qr-styled",
"application/json",
bytes.NewBuffer(body),
)
if err != nil {
panic(err)
}
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
fmt.Println(string(data[:100]))
}即時 QR碼預覽
立即嘗試使用 Go 產生 QR碼。
QR碼預覽
原生函式庫 vs API
比較使用 Go QR碼函式庫與 QRCode.fun API。
| 功能 | 原生函式庫 | QRCode.fun API |
|---|---|---|
| 設定複雜度 | go get + import | 單次 HTTP 請求 |
| 自訂 | 大小、糾錯等級 | 完整樣式:顏色、形狀、標誌 |
| 離線支援 | 是 | 需要網路 |
| 維護 | 更新 go.mod | 始終保持最新 |
| 輸出格式 | PNG | PNG, SVG |
Go QR碼使用情境
Go 應用中 QR碼的常見情境。
微服務
在 Go 微服務中產生 QR碼,用於 API 回應、Webhook 和事件驅動架構。
CLI 工具
建構命令列工具,產生 QR碼用於 Wi-Fi 共享、URL 縮短或終端機顯示。
雲端函式
使用 Go 將 QR碼產生部署為 AWS Lambda 或 Google Cloud Functions 上的無伺服器函式。
DevOps 與基礎建設
為部署 URL、監控儀表板和設定端點產生 QR碼。
常見問題
關於使用 Go 產生 QR碼的常見問題。
skip2/go-qrcode 是最受歡迎的 Go QR碼函式庫。它產生 PNG 影像,支援可設定的大小和糾錯等級。