preface

This is my seventh day in the text challenge, hi, I’m the composer Kind of Sun. In the last article, we talked about how to access GORM and write an interface to get a list of users. In this article, we’re going to connect to Redis and write an interface to return a graphic verification code

1. Introduction

Redis is a noSQL database used for data cache installation:

Docker run -p 6379:6379 -d redis:latest redis-server docker container update --restart=always The name of the containerCopy the code

Install go’s Redis library

    go get github.com/go-redis/redis
Copy the code

(2). The graphic verification code is a means to prevent crawler throttling, and a Base64 code is generated and returned to the front end

2. Initialize the Redis link

(1). Add global variables driven by Redis

Add to global/globalVar:

    Redis  *redis.Client
Copy the code

(2). Write initialization Redis link

Add in initialize/ Redis

package initialize

import (
	"fmt"
	"github.com/fatih/color"
	"github.com/go-redis/redis"
	"go_gin/global"
)

func InitRedis(a) {
	addr := fmt.Sprintf("%s:%d", global.Settings.RedisInfo.Host, global.Settings.RedisInfo.Port)
	// Generate the Redis client
	global.Redis = redis.NewClient(&redis.Options{
		Addr:     addr,
		Password: "".// no password set
		DB:       0.// use default DB
	})
	/ / links to redis
	_, err := global.Redis.Ping().Result()
	iferr ! =nil {
		color.Red("[InitRedis] link redis exception :")
		color.Yellow(err.Error())
	}
}
Copy the code

Ps: global Settings. RedisInfo is yaml redis configuration \

(3). Test

Import InitRedis in main.go

//6. Initialize redis
initialize.InitRedis()
Copy the code

If main.go fails, the redis link is successful

2. Requirements analysis

Graphic verification codes are usually added at login, so let’s redefine the PasswordLoginForm structure and add captCHA,captcha_id, and PasswordLoginForm to forms/user.go Struct changed to:

package forms

type PasswordLoginForm struct {
	Mobile    string `form:"mobile" json:"mobile" binding:"required,mobile"` // The mobile phone number format can be found by standard validator
	PassWord  string `form:"password" json:"password" binding:"required,min=3,max=20"`
	Captcha   string `form:"captcha" json:"captcha" binding:"required,min=5,max=5"` / / verification code
	CaptchaId string `form:"captcha_id" json:"captcha_id" binding:"required"`       // Verification code ID
}
Copy the code

Note the following points: 1. The maximum and minimum values of Captcha are both 5, because the bit of the verification code is set to 5. 2

3. Obtain the graphic verification code interface

(1) install the base64Captcha library

"github.com/mojocn/base64Captcha"
Copy the code

(2). Write in Controller /catpcha.go

package controller

import (
	"github.com/gin-gonic/gin"
	"github.com/mojocn/base64Captcha"
	"go.uber.org/zap"
	"go_gin/Response"
	"net/http"
)
// base64Captcha cache object
var store = base64Captcha.DefaultMemStore
// GetCaptcha obtains the verification code
func GetCaptcha(ctx *gin.Context) {
	//
	driver := base64Captcha.NewDriverDigit(80.240.5.0.7.80)
	cp := base64Captcha.NewCaptcha(driver, store)
	// b64s is the base64 encoding of the image
	id, b64s, err := cp.Generate()
	iferr ! =nil {
		zap.S().Errorf("Error generating captcha,:%s", err.Error())
		Response.Err(ctx, http.StatusInternalServerError, 500."Error generating captcha"."")
		return
	}
	Response.Success(ctx, 200."Verification code generation successful", gin.H{
		"captchaId": id,
		"picPath":   b64s,
	})
}
Copy the code

Ps: base64Captcha NewDriverDigit can according to the parameters by adjusting the parameters of the authentication code

5. Verify the graphic verification code

Generating graphic captcha must beCheck the function

Add it in controller/user.go ps:

4. Add a route to the verification code interface

(1). Add to router/base.go

package router

import (
	"github.com/gin-gonic/gin"
	"go_gin/controller"
)

// InitBaseRouter Specifies the route of the graphic verification code
func InitBaseRouter(Router *gin.RouterGroup) {
	BaseRouter := Router.Group("base")
	{
		BaseRouter.GET("captcha", controller.GetCaptcha)
	}

}
Copy the code

Add InitBaseRouter to initialize/ Router

Ps: Add the verification code to the base routing group

Finally – verification of results

(1). Test redis Settings and values

Add in main.goPs: redis.set () the third position argument is the expiration time, time.second is a Second you can try the comment time.sleep() function to see if it can print the data

(2). Test graphic verification code interface

Postman open:http://192.168.0.125:8022/v1/base/captcha

When the id is returned, and the base64 verification code succeeds

Ps: You can also write oneimgHTML tag to write render Base64 graphics captcha

(3). Verify the login interface again(PasswordLoginForm structure was changed earlier)

If you found any of these articles useful, please give them a thumbs up and leave a comment