Generating a QR Code in Go is a simple process thanks to open-source libraries like github.com/skip2/go-qrcode. In this article, we’ll go step by step through how to create a QR Code and save it as a PNG image.
1. Install the Library
First, you need to install the go-qrcode library. Run the following command:
go get -u github.com/skip2/go-qrcode
2. Writing the Go Code
Next, you can write a simple program to generate a QR Code containing some text (for example, a URL) and save it to disk.
package main
import (
"github.com/skip2/go-qrcode"
"log"
)
func main() {
err := qrcode.WriteFile("https://example.com", qrcode.Medium, 256, "qrcode.png")
if err != nil {
log.Fatal(err)
}
}
This code generates a QR Code with medium error correction level (qrcode.Medium), dimensions of 256x256 pixels, and saves it as qrcode.png.
3. Additional Options
You can also directly generate PNG bytes or obtain the image as a base64 string:
png, err := qrcode.Encode("https://example.com", qrcode.High, 256)
if err != nil {
log.Fatal(err)
}
// Use png as []byte or write it to a file
Conclusion
With just a few steps, you can generate QR Codes in Go quickly and efficiently. The go-qrcode library is easy to use and provides useful features for customizing the quality and size of the generated code.