Home > Backend Development > Golang > Use the Gin framework to implement QR code generation and scanning functions

Use the Gin framework to implement QR code generation and scanning functions

王林
Release: 2023-06-23 08:18:09
Original
1824 people have browsed it

In modern society, QR codes have become a common method of information transmission. It can deliver information quickly and facilitate people's lives. For developers, how to generate and scan QR codes conveniently and quickly is an issue that needs to be considered. In this article, we will introduce how to use the Gin framework to realize the generation and scanning functions of QR codes.

  1. Install the Gin framework and related libraries

First, we need to install the Gin framework and related libraries. Execute the following command to complete the installation:

go get -u github.com/gin-gonic/gin
go get -u github.com/skip2/go-qrcode
go get -u github.com/fogleman/gg
Copy after login

Among them, gin is the Gin framework, go-qrcode is the library for generating QR codes, and gg is the library for generating pictures.

  1. Generate QR code

Next we need to write the code to generate the QR code. We can define a function that generates a QR code. The code is as follows:

func generateQRCode(c *gin.Context) {
    // 获取传递的参数
    content := c.Query("content")
    size := c.DefaultQuery("size", "256")

    // 生成二维码图片
    qr, err := qrcode.New(content, qrcode.Medium)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{
            "error": err.Error(),
        })
        return
    }
    qr.DisableBorder = true
    img := qr.Image(int(size))

    // 将图片存储为PNG格式
    buffer := new(bytes.Buffer)
    err = png.Encode(buffer, img)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{
            "error": err.Error(),
        })
        return
    }

    // 将图片作为响应输出给客户端
    c.Data(http.StatusOK, "image/png", buffer.Bytes())
}
Copy after login

In the above code, we read the passed content parameter as the content of the QR code, and also You can set the size of the QR code through the size parameter. The default value is 256. We use the qrcode.New function in the go-qrcode library to generate a QR code image. We can also remove the image border through the DisableBorder attribute. Finally, we use the png.Encode function in the gg library to store the image in PNG format, and use the c.Data method of the Gin framework to store the image as The response is output to the client.

  1. Scan the QR code

After generating the QR code, we need to write the code for scanning the QR code. We can add a route for scanning QR codes in the route, the code is as follows:

func scanQRCode(c *gin.Context) {
    // 读取上传的图片文件
    file, err := c.FormFile("file")
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{
            "error": err.Error(),
        })
        return
    }

    // 打开上传的文件
    f, err := file.Open()
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{
            "error": err.Error(),
        })
        return
    }
    defer f.Close()

    // 读取文件内容并解码
    img, err := png.Decode(f)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{
            "error": err.Error(),
        })
        return
    }
    content, err := qrcode.Decode(img)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{
            "error": err.Error(),
        })
        return
    }

    // 将解码后的内容作为响应输出给客户端
    c.JSON(http.StatusOK, gin.H{
        "content": content,
    })
}
Copy after login

In the above code, we use the FormFile function of the Gin framework to read the uploaded image file. We then decode the file content through the png.Decode function, and use the qrcode.Decode function in the go-qrcode library to output the decoded content as a response. to the client.

  1. Complete code

After completing the above steps, we write the complete code, as follows:

package main

import (
    "bytes"
    "net/http"
    "strconv"

    "github.com/gin-gonic/gin"
    "github.com/fogleman/gg"
    "github.com/skip2/go-qrcode"
)

func main() {
    r := gin.Default()

    // 生成二维码
    r.GET("/qrcode", generateQRCode)

    // 扫描二维码
    r.POST("/qrcode", scanQRCode)

    r.Run()
}

func generateQRCode(c *gin.Context) {
    // 获取传递的参数
    content := c.Query("content")
    sizeStr := c.DefaultQuery("size", "256")

    // 将size参数转换为int类型
    size, err := strconv.Atoi(sizeStr)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{
            "error": err.Error(),
        })
        return
    }

    // 生成二维码图片
    qr, err := qrcode.New(content, qrcode.Medium)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{
            "error": err.Error(),
        })
        return
    }
    qr.DisableBorder = true
    img := qr.Image(size)

    // 将图片存储为PNG格式
    buffer := new(bytes.Buffer)
    err = png.Encode(buffer, img)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{
            "error": err.Error(),
        })
        return
    }

    // 将图片作为响应输出给客户端
    c.Data(http.StatusOK, "image/png", buffer.Bytes())
}

func scanQRCode(c *gin.Context) {
    // 读取上传的图片文件
    file, err := c.FormFile("file")
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{
            "error": err.Error(),
        })
        return
    }

    // 打开上传的文件
    f, err := file.Open()
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{
            "error": err.Error(),
        })
        return
    }
    defer f.Close()

    // 读取文件内容并解码
    img, err := png.Decode(f)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{
            "error": err.Error(),
        })
        return
    }
    content, err := qrcode.Decode(img)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{
            "error": err.Error(),
        })
        return
    }

    // 将解码后的内容作为响应输出给客户端
    c.JSON(http.StatusOK, gin.H{
        "content": content,
    })
}
Copy after login

In the above code, we use The Gin framework defines two processing functions generateQRCode and scanQRCode. In the generateQRCode function, we use the go-qrcode library to generate a QR code, and use the gg library to generate a PNG format image. In the scanQRCode function, we parse the uploaded QR code image, read the QR code content, and finally output the content as a response through the c.JSON method of the Gin framework. client. We use the routing function of the Gin framework in the main function to define the GET and POST requests under the qrcode path corresponding to the functions of generating QR codes and scanning QR codes respectively.

  1. Usage effect

After completing the above code, we can start the service through the following command:

go run main.go
Copy after login

Then access http in the browser: //localhost:8080/qrcode?content=HelloWorld can generate a QR code. If we want to scan the QR code we just generated, we need to first save the QR code as a PNG format image file, and then use tools such as curl or Postman to upload the image file, for example:

curl -X POST -F "file=@qrcode.png" http://localhost:8080/qrcode
Copy after login

In this way, we You can get the content contained in the QR code in the returned response.

So far, we have successfully implemented the QR code generation and scanning functions using the Gin framework, which facilitates our development work.

The above is the detailed content of Use the Gin framework to implement QR code generation and scanning functions. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template