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:

Leave a Reply

Your email address will not be published. Required fields are marked *