安装
使用 go get 安装 Go 二维码库。
go get
go get github.com/skip2/go-qrcode使用 Go 生成二维码
使用 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 中生成二维码
从 Go 调用 QRCode.fun API 生成样式化二维码。
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]))
}实时二维码预览
立即尝试使用 Go 生成二维码。
二维码预览
原生库 vs API
比较使用 Go 二维码库与 QRCode.fun API。
| 功能 | 原生库 | QRCode.fun API |
|---|---|---|
| 设置复杂度 | go get + import | 单次 HTTP 请求 |
| 自定义 | 大小、纠错等级 | 完整样式:颜色、形状、徽标 |
| 离线支持 | 是 | 需要互联网 |
| 维护 | 更新 go.mod | 始终保持最新 |
| 输出格式 | PNG | PNG, SVG |
Go 二维码使用场景
Go 应用中二维码的常见场景。
微服务
在 Go 微服务中生成二维码,用于 API 响应、Webhook 和事件驱动架构。
CLI 工具
构建命令行工具,生成二维码用于 Wi-Fi 共享、URL 缩短或终端显示。
云函数
使用 Go 将二维码生成部署为 AWS Lambda 或 Google Cloud Functions 上的无服务器函数。
DevOps 与基础设施
为部署 URL、监控仪表盘和配置端点生成二维码。
常见问题
关于使用 Go 生成二维码的常见问题。
skip2/go-qrcode 是最流行的 Go 二维码库。它生成 PNG 图像,支持可配置的大小和纠错等级。