Home > Backend Development > Golang > Verification code usage examples in Gin framework

Verification code usage examples in Gin framework

PHPz
Release: 2023-06-23 08:10:45
Original
1878 people have browsed it

With the popularization of the Internet, verification codes have become a necessary process for login, registration, password retrieval and other operations. In the Gin framework, implementing the verification code function has become extremely simple.

This article will introduce how to use a third-party library to implement the verification code function in the Gin framework, and provide sample code for readers' reference.

1. Install dependent libraries

Before using the verification code, we need to install a third-party library goCaptcha.

To install goCaptcha, you can use the go get command:

$ go get -u github.com/mojocn/base64Captcha
Copy after login

2. Generate verification code

goCaptcha provides three verification code types, including numeric verification code, letter verification code and Alphanumeric verification code. Next, we will take the digital verification code as an example to demonstrate how to generate the verification code.

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    b64 "github.com/mojocn/base64Captcha"
)

func main() {
    // 以下是生成验证码的代码
    driver := b64.NewDriverDigit(80, 240, 6, 0.7, 80)
    captcha := b64.NewCaptcha(driver, b64.DefaultMemStore)
    id, b64s, err := captcha.Generate()
    if err != nil {
        fmt.Println(err.Error())
    }
    fmt.Println(id, b64s)
}
Copy after login

In the above code, we use the NewDriverDigit function to create a verification code generator. The parameters of the function successively represent the image width, height, verification code length, noise intensity and number of interference lines. Then we use the NewCaptcha function to create a verification code object and call the Generate method to generate the verification code.

3. Send the verification code to the client

After generating the verification code, we need to send it to the client. In the Gin framework, you can use the ResponseWriter.Write function to write the response body.

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    b64 "github.com/mojocn/base64Captcha"
)

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

    // 以下是生成验证码的代码
    driver := b64.NewDriverDigit(80, 240, 6, 0.7, 80)
    captcha := b64.NewCaptcha(driver, b64.DefaultMemStore)
    router.GET("/captcha", func(c *gin.Context) {
        id, b64s, err := captcha.Generate()
        if err != nil {
            fmt.Println(err.Error())
            c.String(500, err.Error())
            return
        }
        c.SetCookie("captcha_id", id, 300, "/", "localhost", false, true)
        c.Data(200, "image/png", []byte(b64s))
    })

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

In the above code, we created a /captcha route, passed the verification code ID through the SetCookie method, and wrote the generated text verification code into the response body through the ResponseWriter object.

4. Verify the verification code

When the user enters the verification code in the form and submits it, we need to obtain the verification code through the verification code ID and verify its correctness. In Go, we can use MemStore objects to store and retrieve verification codes.

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    b64 "github.com/mojocn/base64Captcha"
)

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

    // 以下是生成验证码的代码
    driver := b64.NewDriverDigit(80, 240, 6, 0.7, 80)
    captcha := b64.NewCaptcha(driver, b64.DefaultMemStore)
    router.GET("/captcha", func(c *gin.Context) {
        id, b64s, err := captcha.Generate()
        if err != nil {
            fmt.Println(err.Error())
            c.String(500, err.Error())
            return
        }
        c.SetCookie("captcha_id", id, 300, "/", "localhost", false, true)
        c.Data(200, "image/png", []byte(b64s))
    })

    // 以下是验证验证码的代码
    router.POST("/login", func(c *gin.Context) {
        captchaId, err := c.Cookie("captcha_id")
        if err != nil {
            fmt.Println(err.Error())
            c.String(400, "未生成验证码")
            return
        }
        captchaVal := c.PostForm("captcha_val")
        if captchaVal == "" {
            c.String(400, "请输入验证码")
            return
        }
        if !captcha.Verify(captchaId, captchaVal) {
            c.String(400, "验证码错误")
            return
        }
        c.String(200, "登录成功")
    })

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

In the above code, we created a /login route, which first obtains the verification code ID through Cookie, then obtains the verification code entered by the user through PostForm, and finally uses the Verify method of the verification code object to verify the verification. code correctness.

5. Summary

This article introduces the method of using goCaptcha to implement the verification code function in the Gin framework. First generate the verification code generator through the NewDriverDigit function, then use the NewCaptcha function to create the verification code object, and use the Generate method to generate the verification code. Finally, the verification code is sent to the client through ResponseWriter, the verification code ID is passed through Cookie, the MemStore object is used to store the verification code, and the correctness of the verification code is verified when logging in.

In actual development, we can customize various parameters of the verification code according to needs and combine it with other functions to provide users with a richer functional experience.

The above is the detailed content of Verification code usage examples in Gin framework. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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