Home Backend Development Golang Verification code usage examples in Gin framework

Verification code usage examples in Gin framework

Jun 23, 2023 am 08:10 AM
Verification code Example gin 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
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!

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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if Google Chrome does not display the verification code image? Chrome browser does not display the verification code? What should I do if Google Chrome does not display the verification code image? Chrome browser does not display the verification code? Mar 13, 2024 pm 08:55 PM

What should I do if Google Chrome does not display the verification code image? Sometimes you need a verification code to log in to a web page using Google Chrome. Some users find that Google Chrome cannot display the content of the image properly when using image verification codes. What should be done? The editor below will introduce how to deal with the Google Chrome verification code not being displayed. I hope it will be helpful to everyone! Method introduction: 1. Enter the software, click the "More" button in the upper right corner, and select "Settings" in the option list below to enter. 2. After entering the new interface, click the "Privacy Settings and Security" option on the left. 3. Then click "Website Settings" on the right

Use the Gin framework to implement automatic generation of API documents and document center functions Use the Gin framework to implement automatic generation of API documents and document center functions Jun 23, 2023 am 11:40 AM

With the continuous development of Internet applications, the use of API interfaces is becoming more and more popular. During the development process, in order to facilitate the use and management of interfaces, the writing and maintenance of API documents has become increasingly important. The traditional way of writing documents requires manual maintenance, which is inefficient and error-prone. In order to solve these problems, many teams have begun to use automatic generation of API documents to improve development efficiency and code quality. In this article, we will introduce how to use the Gin framework to implement automatic generation of API documents and document center functions. Gin is one

Why can't I receive the verification code on my phone? Why can't I receive the verification code on my phone? Aug 17, 2023 pm 02:49 PM

Failure to receive the verification code on your mobile phone is caused by network problems, mobile phone settings problems, mobile phone operator problems and personal settings problems. Detailed introduction: 1. Network problems. The network environment where the mobile phone is located is unstable or the signal is weak, which may cause the verification code to be unable to be delivered in time; 2. Mobile phone setting problems. The text message or voice function of the mobile phone is accidentally turned off, or the The verification code sending number is added to the blacklist, resulting in the verification code not being received normally; 3. Mobile phone operator issues, the mobile phone operator may have malfunctions or maintenance, resulting in the verification code not being delivered in time, etc.

Detailed explanation of reverse proxy and request forwarding in Gin framework Detailed explanation of reverse proxy and request forwarding in Gin framework Jun 23, 2023 am 11:43 AM

With the rapid development of web applications, more and more enterprises tend to use Golang language for development. In Golang development, using the Gin framework is a very popular choice. The Gin framework is a high-performance web framework that uses fasthttp as the HTTP engine and has a lightweight and elegant API design. In this article, we will delve into the application of reverse proxy and request forwarding in the Gin framework. The concept of reverse proxy The concept of reverse proxy is to use the proxy server to make the client

Can virtual numbers receive verification codes? Can virtual numbers receive verification codes? Jan 02, 2024 am 10:22 AM

The virtual number can receive the verification code. As long as the mobile phone number filled in during registration complies with the regulations and the mobile phone number can be connected normally, you can receive the SMS verification code. However, you need to be careful when using virtual mobile phone numbers. Some websites do not support virtual mobile phone number registration, so you need to choose a regular virtual mobile phone number service provider.

Use the Gin framework to implement internationalization and multi-language support functions Use the Gin framework to implement internationalization and multi-language support functions Jun 23, 2023 am 11:07 AM

With the development of globalization and the popularity of the Internet, more and more websites and applications have begun to strive to achieve internationalization and multi-language support functions to meet the needs of different groups of people. In order to realize these functions, developers need to use some advanced technologies and frameworks. In this article, we will introduce how to use the Gin framework to implement internationalization and multi-language support capabilities. The Gin framework is a lightweight web framework written in Go language. It is efficient, easy to use and flexible, and has become the preferred framework for many developers. besides,

PHP image processing case: How to implement the verification code function of images PHP image processing case: How to implement the verification code function of images Aug 17, 2023 pm 12:09 PM

PHP image processing case: How to implement the verification code function of images. With the rapid development of the Internet, verification codes have become one of the important means to protect website security. Verification code is a verification method that uses image recognition technology to determine whether the user is a real user. This article will introduce how to use PHP to implement the verification code function of images, and come with code examples. Introduction A verification code is a picture containing random characters. The user needs to enter the characters in the picture to pass the verification. The main process of implementing verification code includes generating random characters and drawing characters into pictures.

PHP Development Guide: Implementing Verification Code Login PHP Development Guide: Implementing Verification Code Login Jul 01, 2023 am 09:27 AM

With the development of the Internet and the popularity of smartphones, the verification code login function is adopted by more and more websites and applications. Verification code login is a login method that verifies the user's identity by entering the correct verification code to improve security and prevent malicious attacks. In PHP development, implementing a simple verification code login function is not complicated and can be completed through the following steps. Create a database table First, we need to create a table in the database to store verification code information. The table structure can contain the following fields: id: auto-incrementing primary key phon

See all articles