Skip to content

Instantly share code, notes, and snippets.

@ghyghoo8
Created March 21, 2017 08:15
Show Gist options
  • Save ghyghoo8/28a15e63f7b4f0e785e643a5ecd5d3f6 to your computer and use it in GitHub Desktop.
Save ghyghoo8/28a15e63f7b4f0e785e643a5ecd5d3f6 to your computer and use it in GitHub Desktop.
qrcode-demo
package main
import (
//"bytes"
qrcode "github.com/skip2/go-qrcode"
"crypto/rand"
"fmt"
//"image"
//"image/png"
"os"
"runtime"
)
func randStr(strSize int, randType string) string {
var dictionary string
if randType == "alphanum" {
dictionary = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
}
if randType == "alpha" {
dictionary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
}
if randType == "number" {
dictionary = "0123456789"
}
var bytes = make([]byte, strSize)
rand.Read(bytes)
for k, v := range bytes {
bytes[k] = dictionary[v%byte(len(dictionary))]
}
return string(bytes)
}
func main() {
// maximize CPU usage for maximum performance
runtime.GOMAXPROCS(runtime.NumCPU())
// generate a random string - preferably 6 or 8 characters
randomStr := randStr(6, "alphanum")
fmt.Println(randomStr)
// generate the link or any data you want to
// encode into QR codes
// in this example, we use an example of making purchase by QR code.
// Replace the stuff2buy with yours.
stuff2buy := "stuffpurchaseby?userid=" + randomStr + "&issuer=SomeBigSuperMarket"
PathExists("./QRPNG/")
pngName := "./QRPNG/QRImg_" + randomStr + ".png"
// https://github.com/skip2/go-qrcode
err := qrcode.WriteFile(stuff2buy, qrcode.Medium, 256, pngName)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// everything ok
fmt.Println("QR code generated and saved to " + pngName)
}
func PathExists(path string) (bool, error) {
_, err := os.Stat(path)
if err != nil && os.IsNotExist(err) {
os.MkdirAll(path, 0777)
}
return true, nil
}
@ghyghoo8
Copy link
Author

生成二维码

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment