Golang 使用 go-qrcode 生成二维码

yufei       4 年 前       2343

go-qrcode 项目地址 https://github.com/skip2/go-qrcode

基本使用

package main

import (
    qrcode "github.com/skip2/go-qrcode"
    "image/color"
    "log"
)

func main() {
    // 1. 生成一张 png 图片
    //var png []byte
    _, err := qrcode.Encode("https://www.twle.cn", qrcode.Medium, 256)
    if err != nil {
        log.Fatal(err)
    }

    // 2. 写入文件
    err = qrcode.WriteFile("https://www.twle.cn", qrcode.Medium, 256, "qr.png")
    if err != nil {
        log.Fatal(err)
    }

    // 3. 可以自定义前景色和背景色
    err = qrcode.WriteColorFile("https://www.twle.cn",
        qrcode.Medium,
        256,
        color.Black,
        color.White,
        "qr.png")
}

创建一个 HTTP 服务

package main

import (
    qrcode "github.com/skip2/go-qrcode"
    "image/color"
    "log"
    "net/http"
)

func GenQrcode(w http.ResponseWriter, r *http.Request) {

    text := r.FormValue("text")
    if len(text) == 0 {
        w.WriteHeader(http.StatusNoContent)
        return
    }
    var q *qrcode.QRCode
    q, err := qrcode.New(text, qrcode.Medium)
    if err != nil {
        w.WriteHeader(http.StatusNoContent)
        return
    }
    q.ForegroundColor = color.Black
    q.BackgroundColor = color.White
    q.Write(128, w)
}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", GenQrcode)

    log.Println("listen at :8080")
    err := http.ListenAndServe(":8080", mux)
    if err != nil {
        log.Fatal(err)
    }
}

然后访问

http://localhost:8080/?text=a
目前尚无回复
简单教程 = 简单教程,简单编程
简单教程 是一个关于技术和学习的地方
现在注册
已注册用户请 登入
关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

  简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2022 简单教程 twle.cn All Rights Reserved.