搜尋
首頁後端開發Golang使用Gin框架實現二維碼生成和掃描功能

使用Gin框架實現二維碼生成和掃描功能

Jun 23, 2023 am 08:18 AM
二維碼生成gin框架掃描功能

在現代社會中,二維碼已經成為了常見的一種訊息傳遞方式。它可以快速地傳遞訊息,方便了人們的生活。對於開發者來說,怎麼方便快速地產生和掃描二維碼,是一個需要考慮的問題。在本文中,我們將介紹如何使用Gin框架來實現二維碼的生成和掃描功能。

  1. 安裝Gin框架和相關函式庫

首先,我們需要安裝Gin框架和相關函式庫。執行下列指令即可完成安裝:

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

其中,gin是Gin框架,go-qrcode是產生二維碼的函式庫,gg是產生圖片的函式庫。

  1. 產生二維碼

接下來我們需要寫一個產生二維碼的程式碼。我們可以定義一個產生二維碼的函數,其程式碼如下:

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())
}

在上述程式碼中,我們讀取了傳遞的content參數作為二維碼的內容,同時也可以透過size參數來設定二維碼的大小,預設值為256。我們使用go-qrcode庫中的qrcode.New函數來產生二維碼圖片。我們也可以透過DisableBorder屬性來去掉圖片邊框。最後,我們使用gg庫中的png.Encode函數將圖片以PNG格式進行存儲,並透過Gin框架的c.Data方法將圖片作為響應輸出給客戶端。

  1. 掃描二維碼

在生成完二維碼之後,我們需要寫一個掃描二維碼的程式碼。我們可以在路由中新增一個掃描二維碼的路由,其程式碼如下:

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,
    })
}

在上述程式碼中,我們使用Gin框架的FormFile函數讀取上傳的圖片檔案。我們再透過png.Decode函數對檔案內容進行解碼,使用go-qrcode庫中的qrcode.Decode函數將解碼後的內容作為回應輸出給客戶端。

  1. 完整程式碼

在上述步驟完成之後,我們進行程式碼的完整編寫,如下:

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,
    })
}

在上述程式碼中,我們使用了Gin框架來定義兩個處理函數generateQRCodescanQRCode。在generateQRCode函數中,我們使用go-qrcode函式庫產生了二維碼,並使用gg函式庫產生了PNG格式的圖片。而在scanQRCode函數中,我們解析上傳的二維碼圖片,並讀取二維碼內容,最後將內容透過Gin框架的c.JSON方法作為回應輸出給客戶端。我們在主函數中使用Gin框架的路由函數來定義了qrcode路徑下的GET和POST請求分別對應到產生二維碼和掃描二維碼的功能。

  1. 使用效果

在完成以上程式碼之後,我們可以透過以下指令來啟動服務:

go run main.go

然後在瀏覽器中存取http: //localhost:8080/qrcode?content=HelloWorld即可產生一個二維碼。如果要掃描剛才產生的二維碼,我們需要先將該二維碼儲存為PNG格式圖片文件,然後使用curl或Postman等工具來上傳圖片文件,例如:

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

這樣,我們就可以在傳回的回應中得到二維碼中所包含的內容。

至此,我們已經使用Gin框架成功實現了二維碼的生成和掃描功能,為我們的開發工作提供了便利。

以上是使用Gin框架實現二維碼生成和掃描功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
去其他語言:比較分析去其他語言:比較分析Apr 28, 2025 am 12:17 AM

goisastrongchoiceforprojectsneedingsimplicity,績效和引發性,butitmaylackinadvancedfeatures and ecosystemmaturity.1)

比較以其他語言的靜態初始化器中的初始化功能比較以其他語言的靜態初始化器中的初始化功能Apr 28, 2025 am 12:16 AM

Go'sinitfunctionandJava'sstaticinitializersbothservetosetupenvironmentsbeforethemainfunction,buttheydifferinexecutionandcontrol.Go'sinitissimpleandautomatic,suitableforbasicsetupsbutcanleadtocomplexityifoverused.Java'sstaticinitializersoffermorecontr

GO中初始功能的常見用例GO中初始功能的常見用例Apr 28, 2025 am 12:13 AM

thecommonusecasesfortheinitfunctionoare:1)加載configurationfilesbeforeThemainProgramStarts,2)初始化的globalvariables和3)runningpre-checkSorvalidationsbeforEtheprofforeTheProgrecce.TheInitFunctionIsautefunctionIsautomentycalomationalmatomatimationalycalmatemationalcalledbebeforethemainfuniinfuninfuntuntion

GO中的頻道:掌握際際交流GO中的頻道:掌握際際交流Apr 28, 2025 am 12:04 AM

ChannelsarecrucialingoforenablingsafeandefficityCommunicationBetnewengoroutines.theyfacilitateSynChronizationAndManageGoroutIneLifeCycle,EssentialforConcurrentProgramming.ChannelSallSallSallSallSallowSallowsAllowsEnderDendingAndReceivingValues,ActassignalsignalsforsynChronization,and actassignalsynChronization and andsupppor

包裝錯誤:將上下文添加到錯誤鏈中包裝錯誤:將上下文添加到錯誤鏈中Apr 28, 2025 am 12:02 AM

在Go中,可以通過errors.Wrap和errors.Unwrap方法來包裝錯誤並添加上下文。 1)使用errors包的新功能,可以在錯誤傳播過程中添加上下文信息。 2)通過fmt.Errorf和%w包裝錯誤,幫助定位問題。 3)自定義錯誤類型可以創建更具語義化的錯誤,增強錯誤處理的表達能力。

使用GO開發時的安全考慮使用GO開發時的安全考慮Apr 27, 2025 am 12:18 AM

Gooffersrobustfeaturesforsecurecoding,butdevelopersmustimplementsecuritybestpracticeseffectively.1)UseGo'scryptopackageforsecuredatahandling.2)Manageconcurrencywithsynchronizationprimitivestopreventraceconditions.3)SanitizeexternalinputstoavoidSQLinj

了解GO的錯誤接口了解GO的錯誤接口Apr 27, 2025 am 12:16 AM

Go的錯誤接口定義為typeerrorinterface{Error()string},允許任何實現Error()方法的類型被視為錯誤。使用步驟如下:1.基本檢查和記錄錯誤,例如iferr!=nil{log.Printf("Anerroroccurred:%v",err)return}。 2.創建自定義錯誤類型以提供更多信息,如typeMyErrorstruct{MsgstringDetailstring}。 3.使用錯誤包裝(自Go1.13起)來添加上下文而不丟失原始錯誤信息,

並發程序中的錯誤處理並發程序中的錯誤處理Apr 27, 2025 am 12:13 AM

對效率的Handleerrorsinconcurrentgopragrs,UsechannelstocommunicateErrors,enplionErrorWatchers,Instertimeout,UsebufferedChannels和Provideclearrormessages.1)USEchannelelStopassErtopassErrorsErtopassErrorsErrorsErrorsFromGoroutInestOthemainFunction.2)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器