captcha

Documentation: Official

This third party library is interesting. He has many advantages:

  • You can customize the length of the verification code
  • Generated images do not require additional memory storage throughpathCan be generated
  • Using localcache,reloadVerification code
  • Generates a random number using hash as a verification codeID

Quick to use

This third party library, it has a lot of stuff wrapped up, you just need to call it according to your needs.

The verification code ID is generated

type Captcha struct {
	Id      string `json:"id,omitempty"`      // Verification code ID
	ImgUrl  string `json:"img_url,omitempty"` // Captcha image address
	Refresh string `json:"refresh,omitempty"` // Retrieve
	Verify  string `json:"verify,omitempty"`  / / verification
}

//GenerateId
/* @description: Generates verification code Id * @receiver c * @param CTX */
func (c *Captcha) GenerateId(ctx *gin.Context) {
	// Obtain the verification code length
	var length = variable.ConfigYml.GetInt("Captcha.Length")
	// Customize the length of the verification code
	captchaId := captcha.NewLen(length)
	// Provide relevant information
	c.Id = captchaId
	c.ImgUrl = captchaId + ".png"
	c.Refresh = c.ImgUrl + "? reload=1"
	c.Verify = captchaId + "/ Replace here with the correct captcha for verification"
	response.Success(ctx, "Verification code information", c)
}
Copy the code

ID can generate a picture of the corresponding captcha and then verify the captcha in the form of a key. This is still very important.

Get photo

//GetImg
/* @description: the image that generates the verification code * @receiver c * @param CTX */
func (c *Captcha) GetImg(ctx *gin.Context) {
	// Obtain the verification code Id through param
	captchaId := ctx.Param(captchaIdKey)
	// Divide the path into a directory part and a file name part based on the last slash of the path. Example http://localhost:20201/captcha/ JUpvESBqAcPxvSVz5Cy9. PNG
	_, file := path.Split(ctx.Request.URL.Path)
	// Get the extension.png
	ext := path.Ext(file)
	// Get the Id of the path
	id := file[:len(file)-len(ext)]
	// Verify that the parameters are correctly obtained
	if ext == "" || captchaId == "" {
		response.Fail(ctx, http.StatusBadRequest, consts.CaptchaGetParamsInvalidCode, consts.CaptchaGetParamsInvalidMsg)
		return
	}
	// Reload one when it gets a Reload
	ifctx.Query(Reload) ! ="" {
		// Overload generates and remembers new numbers for the given captcha.
		captcha.Reload(id)
	}
	// Set the HTTP protocol
	ctx.Header("Cache-Control"."no-cache, no-store, must-revalidate")
	ctx.Header("Expires"."0")
	var vBytes bytes.Buffer
	if ext == ".png" {
		ctx.Header("Content-Type"."image/png")
		// Write the binary information of the image
		_ = captcha.WriteImage(&vBytes, id, Width, Height)
		// Read the contents of the file and output the method
		http.ServeContent(ctx.Writer, ctx.Request, id+ext, time.Time{}, bytes.NewReader(vBytes.Bytes()))
	}
}
Copy the code

Captcha uses the Captcha ID to generate the binary of the Captcha image. You just need to put the binary information into the HTTP protocol and display it. This operation does not require you to use extra space to store the image.

Verification code

//CheckCode
/* @description: Digit sent by verification code * @receiver c * @param CTX */
func (c *Captcha) CheckCode(ctx *gin.Context) {
	// Obtain the ID and value of the verification code
	captchaId := ctx.Param(captchaIdKey)
	value := ctx.Param(captchaValueKey)
	// Go to memory for validation
	if captcha.VerifyString(captchaId, value) {
		response.Success(ctx, consts.CaptchaCheckParamsOk)
	} else {
		response.Fail(ctx, http.StatusBadRequest, consts.CaptchaCheckParamsInvalidCode, consts.CaptchaCheckParamsInvalidMsg)
	}
}
Copy the code

According to the field value obtained from the request path, Captcha will put captchaId and value into the local memory for query, and return true if it can be found.

Create routing

You can then create a route directly to the captcha.

	// Create a captCHA route
	verifyCode := router.Group("captcha")
	{
		// The verification code service, which does not require special verification parameters, can directly call the controller
		verifyCode.GET("/", (&captcha.Captcha{}).GenerateId)                          // Obtain the verification code ID
		verifyCode.GET("/:captcha_id", (&captcha.Captcha{}).GetImg)                   // Get the image address
		verifyCode.GET("/:captcha_id/:captcha_value", (&captcha.Captcha{}).CheckCode) // Verify the verification code
	}
Copy the code

The whole process is not difficult. Basically be to understand, he this flow is how!

extension

Change memory

He sets the constants CollectNum and Expiration.

  • CollectNumRepresents the number of captcha created to trigger garbage collection. (Number of expired verification codes cleared at one time)
  • ExpirationIndicates the expiration time of the verification code
func init(a) {
	// Customize the memory Settings
	// Set the number of expired verification codes to be cleared at a time
	collectNum := variable.ConfigYml.GetInt("Captcha.CollectNum")
	// Expiration time
	expiration := variable.ConfigYml.GetDuration("Captcha.Expiration")
	// Return a new standard memory store
	s := captcha.NewMemoryStore(collectNum, expiration)
	// Set up a new memory
	captcha.SetCustomStore(s)
}
Copy the code

Create an audio captcha

func (c *Captcha) GetAudio(ctx *gin.Context) {
	// Obtain the verification code Id through param
	captchaId := ctx.Param(captchaIdKey)
	// Divide the path into a directory part and a file name part based on the last slash of the path. Example http://localhost:20201/captcha/ JUpvESBqAcPxvSVz5Cy9. Wav
	_, file := path.Split(ctx.Request.URL.Path)
	// Get the extension.wav
	ext := path.Ext(file)
	// Get the Id of the path
	id := file[:len(file)-len(ext)]
	// Verify that the parameters are correctly obtained
	if ext == "" || captchaId == "" {
		response.Fail(ctx, http.StatusBadRequest, consts.CaptchaGetParamsInvalidCode, consts.CaptchaGetParamsInvalidMsg)
		return
	}
	ctx.Header("Cache-Control"."no-cache, no-store, must-revalidate")
	ctx.Header("Pragma"."no-cache")
	ctx.Header("Expires"."0")
	// Reload one when it gets a Reload
	ifctx.Query(Reload) ! ="" {
		// Overload generates and remembers new numbers for the given captcha.
		captcha.Reload(id)
	}
	var vBytes bytes.Buffer
	if ext == ".wav" {
		ctx.Header("Content-Type"."audio/wav")
		// Write binary information to audio
		_ = captcha.WriteAudio(&vBytes, id, Lang)
		// Read the contents of the file and output the method
		http.ServeContent(ctx.Writer, ctx.Request, id+ext, time.Time{}, bytes.NewReader(vBytes.Bytes()))
	}
}

Copy the code

Refer to the article

Summary of capTCHA verification codes

Golang Http verification code example