search
HomeBackend DevelopmentGolangVerification code usage examples in Gin framework

Verification code usage examples in Gin framework

Jun 23, 2023 am 08:10 AM
Verification codeExamplegin frame

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

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

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

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

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!

Statement
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
Building Scalable Systems with the Go Programming LanguageBuilding Scalable Systems with the Go Programming LanguageApr 25, 2025 am 12:19 AM

Goisidealforbuildingscalablesystemsduetoitssimplicity,efficiency,andbuilt-inconcurrencysupport.1)Go'scleansyntaxandminimalisticdesignenhanceproductivityandreduceerrors.2)Itsgoroutinesandchannelsenableefficientconcurrentprogramming,distributingworkloa

Best Practices for Using init Functions Effectively in GoBest Practices for Using init Functions Effectively in GoApr 25, 2025 am 12:18 AM

InitfunctionsinGorunautomaticallybeforemain()andareusefulforsettingupenvironmentsandinitializingvariables.Usethemforsimpletasks,avoidsideeffects,andbecautiouswithtestingandloggingtomaintaincodeclarityandtestability.

The Execution Order of init Functions in Go PackagesThe Execution Order of init Functions in Go PackagesApr 25, 2025 am 12:14 AM

Goinitializespackagesintheordertheyareimported,thenexecutesinitfunctionswithinapackageintheirdefinitionorder,andfilenamesdeterminetheorderacrossmultiplefiles.Thisprocesscanbeinfluencedbydependenciesbetweenpackages,whichmayleadtocomplexinitializations

Defining and Using Custom Interfaces in GoDefining and Using Custom Interfaces in GoApr 25, 2025 am 12:09 AM

CustominterfacesinGoarecrucialforwritingflexible,maintainable,andtestablecode.Theyenabledeveloperstofocusonbehavioroverimplementation,enhancingmodularityandrobustness.Bydefiningmethodsignaturesthattypesmustimplement,interfacesallowforcodereusabilitya

Using Interfaces for Mocking and Testing in GoUsing Interfaces for Mocking and Testing in GoApr 25, 2025 am 12:07 AM

The reason for using interfaces for simulation and testing is that the interface allows the definition of contracts without specifying implementations, making the tests more isolated and easy to maintain. 1) Implicit implementation of the interface makes it simple to create mock objects, which can replace real implementations in testing. 2) Using interfaces can easily replace the real implementation of the service in unit tests, reducing test complexity and time. 3) The flexibility provided by the interface allows for changes in simulated behavior for different test cases. 4) Interfaces help design testable code from the beginning, improving the modularity and maintainability of the code.

Using init for Package Initialization in GoUsing init for Package Initialization in GoApr 24, 2025 pm 06:25 PM

In Go, the init function is used for package initialization. 1) The init function is automatically called when package initialization, and is suitable for initializing global variables, setting connections and loading configuration files. 2) There can be multiple init functions that can be executed in file order. 3) When using it, the execution order, test difficulty and performance impact should be considered. 4) It is recommended to reduce side effects, use dependency injection and delay initialization to optimize the use of init functions.

Go's Select Statement: Multiplexing Concurrent OperationsGo's Select Statement: Multiplexing Concurrent OperationsApr 24, 2025 pm 05:21 PM

Go'sselectstatementstreamlinesconcurrentprogrammingbymultiplexingoperations.1)Itallowswaitingonmultiplechanneloperations,executingthefirstreadyone.2)Thedefaultcasepreventsdeadlocksbyallowingtheprogramtoproceedifnooperationisready.3)Itcanbeusedforsend

Advanced Concurrency Techniques in Go: Context and WaitGroupsAdvanced Concurrency Techniques in Go: Context and WaitGroupsApr 24, 2025 pm 05:09 PM

ContextandWaitGroupsarecrucialinGoformanaginggoroutineseffectively.1)ContextallowssignalingcancellationanddeadlinesacrossAPIboundaries,ensuringgoroutinescanbestoppedgracefully.2)WaitGroupssynchronizegoroutines,ensuringallcompletebeforeproceeding,prev

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download

Atom editor mac version download

The most popular open source editor