看到几个 Go QRCode 库都不错,直接拿来测试看看了,谢谢你们 💐!

测试代码

  1package main
  2
  3import (
  4	"bytes"
  5	"github.com/boombuler/barcode"
  6	qr2 "github.com/boombuler/barcode/qr"
  7	"github.com/namsral/flag"
  8	"github.com/nfnt/resize"
  9	qr1 "github.com/skip2/go-qrcode"
 10	"github.com/valyala/fasthttp"
 11
 12	"github.com/zc310/fasthttprouter"
 13	"log"
 14
 15	"github.com/zc310/utils"
 16	"image/png"
 17	"net/http"
 18	"strconv"
 19)
 20
 21var port = flag.String("port", ":8080", "")
 22
 23func main() {
 24	flag.Parse()
 25
 26	router := fasthttprouter.New()
 27
 28	router.GET("/qr", qrHandler(v0))
 29	router.GET("/qr/v1", qrHandler(v1))
 30	router.GET("/qr/v2", qrHandler(v2))
 31
 32	server := &fasthttp.Server{Handler: router.Handler}
 33	log.Fatal(server.ListenAndServe(*port))
 34}
 35
 36func qrHandler(f func(t string, s int) ([]byte, error)) fasthttp.RequestHandler {
 37	return func(ctx *fasthttp.RequestCtx) {
 38		s, err := strconv.Atoi(utils.GetString(ctx.QueryArgs().Peek("s")))
 39		if err != nil {
 40			s = 256
 41		}
 42		var t string
 43		t = utils.GetString(ctx.QueryArgs().Peek("t"))
 44		if t == "" {
 45			t = "https://zc310.tech"
 46		}
 47		var b []byte
 48		b, err = f(t, s)
 49		if err != nil {
 50			ctx.Response.SetStatusCode(http.StatusBadRequest)
 51			return
 52		}
 53		ctx.Response.Header.Set("Content-Type", "image/png")
 54		ctx.Write(b)
 55	}
 56
 57}
 58func v1(text string, size int) ([]byte, error) {
 59	var q *qr1.QRCode
 60
 61	q, err := qr1.New(text, qr1.Low)
 62
 63	if err != nil {
 64		return nil, err
 65	}
 66	q.DisableBorder = false
 67	return q.PNG(size)
 68}
 69func v2(text string, s int) ([]byte, error) {
 70	qrCode, _ := qr2.Encode(text, qr2.L, qr2.Auto)
 71	qrCode, _ = barcode.Scale(qrCode, s, s)
 72
 73	encoder := png.Encoder{CompressionLevel: png.BestCompression}
 74
 75	var b bytes.Buffer
 76	err := encoder.Encode(&b, qrCode)
 77
 78	if err != nil {
 79		return nil, err
 80	}
 81
 82	return b.Bytes(), nil
 83}
 84
 85func v0(text string, s int) ([]byte, error) {
 86	qrCode, _ := qr2.Encode(text, qr2.L, qr2.Auto)
 87
 88	qrCode, _ = barcode.Scale(qrCode, 90, 90)
 89
 90	m := resize.Resize(uint(s), uint(s), qrCode, resize.NearestNeighbor)
 91	encoder := png.Encoder{CompressionLevel: png.BestCompression}
 92
 93	var b bytes.Buffer
 94	err := encoder.Encode(&b, m)
 95
 96	if err != nil {
 97		return nil, err
 98	}
 99
100	return b.Bytes(), nil
101}

参数说明

请求样例: http://127.0.0.1:8080/qr?t=http://zc310.tech&s=512

参数说明
t二维码文本
s图片大小 (pixel)

其他教程