Go实战--二维码生成server

QRCode

百度百科: 
QR Code码,是由Denso公司于1994年9月研制的一种矩阵二维码符号,它具有一维条码及其它二维条码所具有的信息容量大、可靠性高、可表示汉字及图象多种文字信息、保密防伪性强等优点。

wiki: 
QR code (abbreviated from Quick Response Code) is the trademark for a type of matrix barcode (or two-dimensional barcode) first designed for the automotive industry in Japan. A barcode is a machine-readable optical label that contains information about the item to which it is attached. A QR code uses four standardized encoding modes (numeric, alphanumeric, byte/binary, and kanji) to efficiently store data; extensions may also be used

从git上搜索了一圈,找到了 三个二维码库,

https://github.com/boombuler/barcode   (stars 421)

https://github.com/skip2/go-qrcode  (stars 396)

https://github.com/tuotoo/qrcode  (stass 62)

然后写了一个二维码生成服务:

/*
# @Time    : 2018/5/16 11:51
# @Author  : Mickel Xiang
# @File    : qrcode_server.go
# @Function: -----------
*/
package main

import (
	bs "encoding/base64"
	"fmt"
	qrcode "github.com/skip2/go-qrcode"
	"log"
	"net/http"
)

func main() {
	http.HandleFunc("/", http_qrcode) //设置访问的路由
	err1 := http.ListenAndServe(":8080", nil)
	if err1 != nil {
		log.Fatal("ListenAndServe:", err1)
	}
}
func http_qrcode(w http.ResponseWriter, req *http.Request) {
	req.ParseForm()
	param, _ := req.Form["str"]
	if param == nil {

		path := "." + req.URL.Path

		fmt.Println("path", path)
		if path == "./favicon.ico" {
			http.NotFound(w, req)
			return
		}

		fmt.Printf("1a")
		http.Redirect(w, req, "/?str=", http.StatusFound)
		return
	} else {
		base641 := param[0]

		var png []byte
		png, err := qrcode.Encode(string(base641), qrcode.Medium, 256)

		if err != nil {
			fmt.Println("error", err)
		}
		encodeString := bs.StdEncoding.EncodeToString(png)

		ls1 := "<!DOCTYPE html><head><meta charset='utf-8' /></head><body><img src='data:image/png;base64,"
		ls2 := "'/></body></html>"
		ls := ls1 + encodeString + ls2
		fmt.Fprintf(w, ls)
	}
}

请求地址:

http://localhost:8080/?str=https://www.baidu.com

猜你喜欢

转载自my.oschina.net/mickelfeng/blog/1813438