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

Use the Gin framework to implement verification code generation and verification functions

PHPz
Release: 2023-06-22 12:01:37
Original
1500 people have browsed it

With the development of the Internet, verification codes have increasingly become a common security verification measure for websites and applications. Verification code is a human-computer interaction technology based on images, sounds, text, etc., with the purpose of preventing malicious attacks and abuse by robots.

In this article, we will introduce how to use the Gin framework of Go language to implement verification code generation and verification functions. Gin is a lightweight web framework that can quickly build RESTful API and WEB applications.

  1. Install the Gin framework

Before we start, we need to install the Gin framework first. You can use the Go command line tool to install:

go get -u github.com/gin-gonic/gin
Copy after login
  1. Implementing the verification code generation function

In order to generate the verification code image, we need to use a third-party library github.com/mojocn /base64Captcha. The library provides multiple verification code types and supports custom parameters. The following is a sample code for generating an image verification code:

package main

import (
    "fmt"
    "time"

    "github.com/gin-gonic/gin"
    "github.com/mojocn/base64Captcha"
)

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

    // 生成验证码图片
    r.GET("/captcha", func(c *gin.Context) {
        // 配置
        driver := base64Captcha.NewDriverDigit(80, 240, 4, 0.5, 80)
        store := base64Captcha.DefaultMemStore
        captcha := base64Captcha.NewCaptcha(driver, store)

        // 生成验证码
        id, b64s, err := captcha.Generate()
        if err != nil {
            c.JSON(500, gin.H{"error": err.Error()})
            return
        }

        // 返回验证码图片
        c.JSON(200, gin.H{
            "id":      id,
            "image":   b64s,
            "expires": time.Now().Add(time.Minute * 5).Unix(),
        })
    })

    r.Run(":8080")
}
Copy after login

In this example, we use the default Memeory storage to store the verification code information (other storage such as Redis can also be used). The number-based CAPTCHA driver creates CAPTCHAs using a width of 80 pixels, a height of 240 pixels, a length of four characters, and a noise intensity of 0.5. The Generate method will return the generated verification code ID, verification code image and error information. Here, we return the verification code image to the client in base64-encoded form, and specify the expiration time in the response.

  1. Implementing the verification code verification function

When the client submits the verification code, it needs to be verified whether the user input matches the generated verification code. Still use the Verify function provided by the github.com/mojocn/base64Captcha library to verify the verification code. Here is a sample code to verify the image captcha:

package main

import (
    "fmt"

    "github.com/gin-gonic/gin"
    "github.com/mojocn/base64Captcha"
)

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

    // 验证验证码
    r.POST("/verify", func(c *gin.Context) {
        var form struct {
            ID   string `form:"id" binding:"required"`
            Code string `form:"code" binding:"required"`
        }
        if err := c.ShouldBind(&form); err != nil {
            c.JSON(400, gin.H{"error": err.Error()})
            return
        }

        // 验证验证码
        if base64Captcha.VerifyCaptcha(form.ID, form.Code) {
            c.JSON(200, gin.H{"success": true})
        } else {
            c.JSON(401, gin.H{"error": "验证码错误"})
        }
    })

    r.Run(":8080")
}
Copy after login

In this example, we define a structure to store the captcha ID and captcha value submitted from the client. Use the ShouldBind function to bind the request body to the structure. If the binding fails, a 400 error is returned. When verifying the verification code, you can use the VerifyCaptcha function to verify whether the verification code value submitted by the client is correct. If the verification is successful, a 200 response is returned; otherwise, a 401 error is returned and the reason for the verification code error is prompted.

  1. Complete code

Combining the above sample codes for generating verification codes and verifying verification codes, we can get a complete code, as shown below:

package main

import (
    "fmt"
    "time"

    "github.com/gin-gonic/gin"
    "github.com/mojocn/base64Captcha"
)

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

    // 生成验证码图片
    r.GET("/captcha", func(c *gin.Context) {
        // 配置
        driver := base64Captcha.NewDriverDigit(80, 240, 4, 0.5, 80)
        store := base64Captcha.DefaultMemStore
        captcha := base64Captcha.NewCaptcha(driver, store)

        // 生成验证码
        id, b64s, err := captcha.Generate()
        if err != nil {
            c.JSON(500, gin.H{"error": err.Error()})
            return
        }

        // 返回验证码图片
        c.JSON(200, gin.H{
            "id":      id,
            "image":   b64s,
            "expires": time.Now().Add(time.Minute * 5).Unix(),
        })
    })

    // 验证验证码
    r.POST("/verify", func(c *gin.Context) {
        var form struct {
            ID   string `form:"id" binding:"required"`
            Code string `form:"code" binding:"required"`
        }
        if err := c.ShouldBind(&form); err != nil {
            c.JSON(400, gin.H{"error": err.Error()})
            return
        }

        // 验证验证码
        if base64Captcha.VerifyCaptcha(form.ID, form.Code) {
            c.JSON(200, gin.H{"success": true})
        } else {
            c.JSON(401, gin.H{"error": "验证码错误"})
        }
    })

    r.Run(":8080")
}
Copy after login
  1. Summary

This article introduces how to use the Gin framework and the github.com/mojocn/base64Captcha library to implement verification code generation and verification functions. Verification code technology is a widely used security verification method, which can effectively prevent robot attacks and malicious abuse. In practice, other verification code types and storage methods can also be selected according to actual needs, and combined with other security measures to enhance the security and reliability of the application.

The above is the detailed content of Use the Gin framework to implement verification code generation and verification 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