Generate QR code with data in Golang
In this article, we are going to demonstrate how to generate Quick response (QR) code using Golang. A QR code is a two-dimensional barcode which store information just like the traditional one-dimensional line barcode. It is initially developed in the Japanese automotive industry, but through the year it has been adopted in other industries. QR codes were approved by ISO in 2000 as an International standard and specs can be found here. For more information on QR code check this wiki page.
As a way to minimize Social Engineering within companies. It is a good idea to use QR codes since humans can’t tell just by looking at a QR code if it is malicious or not. On the other hand, most of the time QR codes contain a URL that will load immediately, leaving the user open to risk. That is why creating an acceptable pretext is important in order to convince a user to trust the QR code.
To generate QR code in Golang, we are going to use go-qrcode library.
Before we start writing codes and import the library, make sure that your GOPATH is set correctly. For more information about setting your GOPATH, please check this articles:
– For MACOS user
– For Windows user
– For Linux user
Importing go-qrcode library
After verifying that your GOPATH is set, open the terminal and enter the following command:
go get -u github.com/skip2/go-qrcode/...
The (…) at the end means wildcard in Go and this will also install all sub packages.
In this example, we are going to write an application that can generate raw PNG bytes and also the ability to start a server that returns an HTML page with the QR code embedded.
QR code webpage Server
We are going to start implementing the server that will be hosting the HTML page. For more information on web service in Go, check out this article.
func startServer() {
router := httprouter.New() // router instance
router.GET("/",sendQRCode) // landing page
fmt.Println("server listening on port 3000")
serverError := http.ListenAndServe(":3000", router)
if serverError != nil {
log.Fatal("Unable to start web server, cause: ", serverError)
}
}
Function that generate the HTML page
If you have already known how web services work in Go, this is very self-explanatory code. It handles the request by generating the QR code image Tag and embedded it into an HTML page.
func sendQRCode(response http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
// generate QR code HTML image tag
qr_code_image_tag := generateQRCodeHtmlImageTag()
// Set response header to Status Ok (200)
response.WriteHeader(http.StatusOK)
// HTML image with embedded QR code
responsePageHtml := "<!DOCTYPE html><html><body><h1>QR Code example Go Dev Tips
</h1>"+qr_code_image_tag+"</body></html>"
// Send HTML response back to client
_,_ = response.Write([]byte(responsePageHtml))
}
Function to generate QR code html image tag
This function generates the QR code HTML image tag itself as a Base 64 string. The website URL in this example is https://www.godevtips.com, but you can choose your own favorite website URL.
func generateQRCodeHtmlImageTag() string {
// websiteURL = https://www.godevtips.com
// imageSize = 256 x 256 pixels
qrCodeImageData, taskError := qrcode.Encode(websiteURL, qrcode.High, imageSize)
if taskError != nil {
log.Fatalln("Error generating QR code. ",taskError)
}
// Encode raw QR code data to base 64
encodedData := base64.StdEncoding.EncodeToString(qrCodeImageData)
return "<img src=\"data:image/png;base64, "+encodedData+"\">"
}
Main function
The main function contains the part the determines which option to launch. In case you will only want to generate the QR raw PNG bytes, you must provide the ‘file’ argument. Otherwise, it will start a server that hosts the resulted QR code HTML page on port 3000.
func main() {
if len(os.Args) == 2 && os.Args[1] == "file" { // Determine which option to launch
// Generate only the raw PNG bytes
outputFileName := "qr_code.png"
taskError := qrcode.WriteFile(websiteURL,qrcode.Medium,imageSize,outputFileName)
if taskError != nil {
log.Fatal("Error generating QR code to file. ",taskError)
} else {
fmt.Println("Qrcode file created!")
}
} else {
startServer()
}
}
Run and test the application
RAW PNG bytes
To generate the raw PNG file, enter the following command in the terminal:
go run qr_code_en.go file
HTML page with QR code
To start the server and host the QR code webpage, open the terminal and execute the following command:
go run qr_code_en.go
Once the server is up and running, open your browser and go to http://localhost:3000/ and you will see the HTML web page. When you scan the QR code, it will launch the GoDevTips webpage.
Visit our GitHub repository for the project source code and clone our repository for all future projects.
Follow us:
Greetings from Florida! I’m bored at work so I decided to browse your blog on my iphone during lunch break. I enjoy the information you provide here and can’t wait to take a look when I get home. I’m surprised at how quick your blog loaded on my cell phone .. I’m not even using WIFI, just 3G .. Anyhow, fantastic site!
Hiya very nice website!! Guy .. Excellent .. Superb .. I’ll bookmark your web site and take the feeds I’m happy to seek out a lot of useful information here within the submit, we’d like work out more strategies in this regard, thank you for sharing. . . . . .
Thanks a bunch for sharing this with all of us you really know what you’re talking about! Bookmarked.
Very well written information. It will be supportive to anyone who employess it, as well as me. Keep up the good work – i will definitely read more posts.
I appreciate, cause I found just what I was looking for. You have ended my four day long hunt! God Bless you man. Have a great day. Bye
It’s really a great and helpful piece of information. I am glad that you shared this useful information with us. Please keep us informed like this. Thank you for sharing.
Excellent goods from you, man. I’ve bear in mind your stuff prior to and you’re just extremely wonderful. I really like what you have got here, certainly like what you’re stating and the way by which you say it. You are making it entertaining and you still take care of to keep it sensible. I can not wait to read much more from you. That is really a wonderful web site.
A great post without any doubt.
you’re really a good webmaster. The site loading speed is amazing. It seems that you’re doing any unique trick. Furthermore, The contents are masterpiece. you’ve done a magnificent job on this topic!
An attention-grabbing discussion is worth comment. I feel that you need to write extra on this topic, it might not be a taboo subject but generally individuals are not enough to speak on such topics. To the next. Cheers
Pretty section of content. I just stumbled upon your blog and in accession capital to assert that I get in fact enjoyed account your blog posts. Anyway I will be subscribing to your feeds and even I achievement you access consistently fast.