This content requires basic knowledge of gin framework and basic knowledge of golang microservices to better understand
1. Introduction of Captcha verification code function
In the front, we explained the architecture of microservices, etc. Here, we will explain the Captcha verification code microservice of the previous mall project . The captcha verification code function is used in the foreground and the backend . It can be extracted and made into a microservice Function
![](https://img-blog.csdnimg.cn/img_convert/7ab6f3f7408afb591d22d8fab01af889.png)
![](https://img-blog.csdnimg.cn/img_convert/7e8d3fe70673529050045d360e48bb57.gif)
![](https://img-blog.csdnimg.cn/img_convert/4d8d89a9c24f20acffd96fd9e70c0e1f.png)
![](https://img-blog.csdnimg.cn/img_convert/2afb9d2b50a343a1d25b2821e57bc634.gif)
edit
This verification code function encapsulates the code captcha.go as follows:
package models
//验证码属性: https://captcha.mojotv.cn/
import (
"github.com/mojocn/base64Captcha"
"image/color"
)
//创建store,保存验证码的位置,默认为mem(内存中)单机部署,如果要布置多台服务器,则可以设置保存在redis中
//var store = base64Captcha.DefaultMemStore
//配置RedisStore, 保存验证码的位置为redis, RedisStore实现base64Captcha.Store接口
var store base64Captcha.Store = RedisStore{}
//获取验证码
func MakeCaptcha(height int, width int, length int) (string, string, error) {
//定义一个driver
var driver base64Captcha.Driver
//创建一个字符串类型的验证码驱动DriverString, DriverChinese :中文驱动
driverString := base64Captcha.DriverString{
Height: height, //高度
Width: width, //宽度
NoiseCount: 0, //干扰数
ShowLineOptions: 2 | 4, //展示个数
Length: length, //长度
Source: "1234567890qwertyuioplkjhgfdsazxcvbnm", //验证码随机字符串来源
BgColor: &color.RGBA{ // 背景颜色
R: 3,
G: 102,
B: 214,
A: 125,
},
Fonts: []string{"wqy-microhei.ttc"}, // 字体
}
driver = driverString.ConvertFonts()
//生成验证码
c := base64Captcha.NewCaptcha(driver, store)
id, b64s, err := c.Generate()
return id, b64s, err
}
//校验验证码
func VerifyCaptcha(id string, VerifyValue string) bool {
// 参数说明: id 验证码id, verifyValue 验证码的值, true: 验证成功后是否删除原来的验证码
if store.Verify(id, VerifyValue, true) {
return true
} else {
return false
}
}
![](https://img-blog.csdnimg.cn/img_convert/c2c15ffeebfee37eccced8637df0b1ef.gif)
If you make this verification code into a microservice, you need to implement the above two methods: get the verification code (MakeCaptcha), verify the verification code (VerifyCaptcha)
2. Create captcha verification code microservice server
-
Create two folders, client (client), server (server)
![](https://img-blog.csdnimg.cn/img_convert/c0a31b3406b25c53975ed4e897cc774a.png)
-
Generate server-side captcha microservice code
Run in the server directory: go-micro new service captcha to generate captcha server code
![](https://img-blog.csdnimg.cn/img_convert/4ea45150bd8fb7804b70d045120f2f56.png)
After running the command, the generated server directory is as follows:
![](https://img-blog.csdnimg.cn/img_convert/821660b055cd05c6ac4025df34acd87c.png)
-
Write proto/captcha.proto file
Write in this file to get the verification code and verify the verification code related code
syntax = "proto3";
package captcha;
option go_package = "./proto/captcha";
service Captcha {
//获取验证码: MakeCaptchaRequest请求, MakeCaptchaRequest返回
rpc MakeCaptcha(MakeCaptchaRequest) returns (MakeCaptchaResponse) {}
//校验验证码: VerifyCaptchaRequest请求, VerifyCaptchaResponse返回
rpc VerifyCaptcha(VerifyCaptchaRequest) returns (VerifyCaptchaResponse) {}
}
//以下具体参数类型参考captcha.go中对应的方法
//获取验证码请求参数
message MakeCaptchaRequest {
//验证码高度
int32 height =1;
//验证码宽度
int32 width = 2;
//验证码长度
int32 length = 3;
}
//获取验证码返回数据
message MakeCaptchaResponse {
//验证码id
string id = 1;
//验证码base64编码
string b64s = 2;
}
//校验验证码请求参数
message VerifyCaptchaRequest {
//验证码id
string id = 1;
//输入的验证码
string verifyValue = 2;
}
//校验验证码返回数据
message VerifyCaptchaResponse {
//校验的结果
bool verifyResult = 1;
}
-
Generate proto related files
Refer to [golang microservices] 7. go-micro framework introduction, go-micro scaffolding, go-micro combined with consul to build a microservice case , run the code under proto in the Makefile under windows : protoc --proto_path=. --micro_out= . --go_out=:. proto/captcha.proto, of course, if you are using go-micro for the first time, you also need to run the code below init (@go xxx) to import related packages
![](https://img-blog.csdnimg.cn/img_convert/9671ef9eb89661ac9598b546648ed96c.png)
![](https://img-blog.csdnimg.cn/c257f4193306482b82badaffc48143b1.png)
-
Initialize the project
Run the command in the captcha directory: go mod init captcha , initialize the project
![](https://img-blog.csdnimg.cn/img_convert/005d28e2cf2297101e0b19b4b28de151.png)
After deleting go.mod, execute the go mod init captcha command again:
![](https://img-blog.csdnimg.cn/img_convert/a7250586ed85188e7ca42ca3c882c059.png)
Run the command : go mod tidy to load the packages required by the project:
![](https://img-blog.csdnimg.cn/img_convert/3cc50a343bc7adc9f4cdfbee523b1ab4.png)
The above said: downloading the package "go-micro.dev/v4" failed, then you need to run the command go get go-micro.dev/v4, specific reference : [golang microservice] 7. Introduction to the go-micro framework, Go-micro scaffolding, go-micro combined with consul to build a micro-service case
here may appear that the import is always reported red , the solution see : golang open mod after the import report red solution
-
Start consul service discovery
Run the command in cmd: consul agent -dev, specific reference: [golang microservice] 5. Microservice service discovery introduction, installation and use of consul, Consul cluster
![](https://img-blog.csdnimg.cn/img_convert/9d7fe3d3f318b5cf6765e680a7c323e6.png)
![](https://img-blog.csdnimg.cn/img_convert/434459b632b703a21cc1ed5323fbb37d.png)
-
Instantiate consul in main.go
Specific reference: [golang microservice] 7. Go-micro framework introduction, go-micro scaffolding, go-micro combined with consul to build a microservice case , the code is as follows:
package main
import (
"captcha/handler"
pb "captcha/proto/captcha"
"go-micro.dev/v4"
"go-micro.dev/v4/logger"
"github.com/go-micro/plugins/v4/registry/consul"
)
var (
service = "captcha"
version = "latest"
)
func main() {
//集成consul
consulReg := consul.NewRegistry()
// Create service
srv := micro.NewService(
micro.Address("127.0.0.1:8081"), //指定微服务的ip: 选择注册服务器地址,也可以不配置,默认为本机,也可以选择consul集群中的client
micro.Name(service),
micro.Version(version),
//注册consul
micro.Registry(consulReg),
)
srv.Init(
micro.Name(service),
micro.Version(version),
)
// Register handler
if err := pb.RegisterCaptchaHandler(srv.Server(), new(handler.Captcha)); err != nil {
logger.Fatal(err)
}
// Run service
if err := srv.Run(); err != nil {
logger.Fatal(err)
}
}
-
handler/captcha.go encapsulates and implements the rpc method in proto/captcha.proto
Refer to the service Captcha method in proto/captcha.proto for implementation, or refer to the method generated in the generated .pb.micro.go for implementation
(1).pb.micro.go reference code:
// Client API for Captcha service
type CaptchaService interface {
// 获取验证码: MakeCaptchaRequest请求, MakeCaptchaRequest返回
MakeCaptcha(ctx context.Context, in *MakeCaptchaRequest, opts ...client.CallOption) (*MakeCaptchaResponse, error)
// 校验验证码: VerifyCaptchaRequest请求, VerifyCaptchaResponse返回
VerifyCaptcha(ctx context.Context, in *VerifyCaptchaRequest, opts ...client.CallOption) (*VerifyCaptchaResponse, error)
}
(2).handler/captcha.go code:
Copy the code of captcha.go in 1. Captcha verification code function introduction to handler/captcha.go, and then modify it.
1) First, import " github.com/mojocn/base64Captcha"
Put " github.com/mojocn/base64Captcha" into import, and then import it through go mod tidy or go get
github.com/mojocn/base64Captcha
2). Configure RedisStore
Copy var store base64Captcha.Store = RedisStore{} into it
//创建store,保存验证码的位置,默认为mem(内存中)单机部署,如果要布置多台服务器,则可以设置保存在redis中
//var store = base64Captcha.DefaultMemStore
//配置RedisStore, 保存验证码的位置为redis, RedisStore实现base64Captcha.Store接口
var store base64Captcha.Store = RedisStore{}
The storage method of redis is used here , so redis needs to be initialized , and the code to implement the method of setting captcha is needed, so models/redisCore.go and models/redisStore.go files need to be created under captcha . For details, refer to: [golang gin framework] 12.Gin mall project-base64Captcha generates graphic verification code and configures Captcha in distributed architecture
Code to initialize redis
The redisCore.go code is as follows:
package models
//redis官网: github.com/go-redis
//下载go-redis: go get github.com/redis/go-redis/v9
//连接redis数据库核心代码
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
"gopkg.in/ini.v1"
"os"
)
//全局使用,就需要把定义成公有的
var ctxRedis = context.Background()
var (
RedisDb *redis.Client
)
//是否开启redis
var redisEnable bool
//自动初始化数据库
func init() {
//加载配置文件
config, iniErr := ini.Load("./conf/app.ini")
if iniErr != nil {
fmt.Printf("Fail to read file: %v", iniErr)
os.Exit(1)
}
//获取redis配置
ip := config.Section("redis").Key("ip").String()
port := config.Section("redis").Key("port").String()
redisEnable, _ = config.Section("redis").Key("redisEnable").Bool()
//判断是否开启redis
if redisEnable {
RedisDb = redis.NewClient(&redis.Options{
Addr: ip + ":" + port,
Password: "", // no password set
DB: 0, // use default DB
})
//连接redis
_, err := RedisDb.Ping(ctxRedis).Result()
//判断连接是否成功
if err != nil {
println(err)
}
}
}
The code of the method to set captcha
The redisStore.go code is as follows:
package models
/**
使用redis需实现Store中的三个方法
type Store interface {
// Set sets the digits for the captcha id.
Set(id string, value string)
// Get returns stored digits for the captcha id. Clear indicates
// whether the captcha must be deleted from the store.
Get(id string, clear bool) string
//Verify captcha's answer directly
Verify(id, answer string, clear bool) bool
}
*/
import (
"context"
"fmt"
"time"
)
var ctx = context.Background()
const CAPTCHA = "captcha:"
type RedisStore struct {
}
//实现设置 captcha 的方法
func (r RedisStore) Set(id string, value string) error {
key := CAPTCHA + id
err := RedisDb.Set(ctx, key, value, time.Minute*2).Err()
return err
}
//实现获取 captcha 的方法
func (r RedisStore) Get(id string, clear bool) string {
key := CAPTCHA + id
//获取 captcha
val, err := RedisDb.Get(ctx, key).Result()
if err != nil {
fmt.Println(err)
return ""
}
//如果clear == true, 则删除
if clear {
err := RedisDb.Del(ctx, key).Err()
if err != nil {
fmt.Println(err)
return ""
}
}
return val
}
//实现验证 captcha 的方法
func (r RedisStore) Verify(id, answer string, clear bool) bool {
v := RedisStore{}.Get(id, clear)
return v == answer
}
Ini.Load is used here to load
Reference: [golang gin framework] 9. Use transactions and go-ini to load .ini configuration files in Gin GORM
3). Implement the business logic code of the verification code method
Copy the method code of captcha.go to obtain the verification code in 1. Captcha verification code function introduction to MakeCaptcha in handler/captcha.go , and then modify it. The code is as follows
//获取验证码的方法
func (e *Captcha) MakeCaptcha(ctx context.Context, req *pb.MakeCaptchaRequest, rsp *pb.MakeCaptchaResponse) error {
//实现业务逻辑代码
//定义一个driver
var driver base64Captcha.Driver
//创建一个字符串类型的验证码驱动DriverString, DriverChinese :中文驱动
driverString := base64Captcha.DriverString{
Height: int(req.Height), //高度
Width: int(req.Width), //宽度
NoiseCount: 0, //干扰数
ShowLineOptions: 2 | 4, //展示个数
Length: int(req.Length), //长度
Source: "1234567890qwertyuioplkjhgfdsazxcvbnm", //验证码随机字符串来源
BgColor: &color.RGBA{ // 背景颜色
R: 3,
G: 102,
B: 214,
A: 125,
},
Fonts: []string{"wqy-microhei.ttc"}, // 字体
}
driver = driverString.ConvertFonts()
//生成验证码
c := base64Captcha.NewCaptcha(driver, store)
id, b64s, err := c.Generate()
//把生成的验证码id,base64编码赋值给返回的rsp参数
rsp.Id = id
rsp.B64S = b64s
return err
}
4). Realize the business logic code of the verification verification code method
Copy the method code of captcha.go verifying the verification code in 1. Captcha verification code function introduction to the MakeCaptcha of handler/captcha.go , and then modify it. The code is as follows:
//校验验证码的方法
func (e *Captcha) VerifyCaptcha(ctx context.Context, req *pb.VerifyCaptchaRequest, rsp *pb.VerifyCaptchaResponse) error {
// 参数说明: id 验证码id, verifyValue 验证码的值, true: 验证成功后是否删除原来的验证码
if store.Verify(req.Id, req.VerifyValue, true) {
rsp.VerifyResult = true //校验成功
} else {
rsp.VerifyResult = false //校验失败
}
return nil
}
4). The complete code is as follows
package handler
import (
"captcha/models"
pb "captcha/proto/captcha"
"context"
"github.com/mojocn/base64Captcha"
"image/color"
)
//创建store,保存验证码的位置,默认为mem(内存中)单机部署,如果要布置多台服务器,则可以设置保存在redis中
//var store = base64Captcha.DefaultMemStore
//配置RedisStore, 保存验证码的位置为redis, RedisStore实现base64Captcha.Store接口
var store base64Captcha.Store = models.RedisStore{}
type Captcha struct{}
//获取验证码的方法
func (e *Captcha) MakeCaptcha(ctx context.Context, req *pb.MakeCaptchaRequest, rsp *pb.MakeCaptchaResponse) error {
//实现业务逻辑代码
//定义一个driver
var driver base64Captcha.Driver
//创建一个字符串类型的验证码驱动DriverString, DriverChinese :中文驱动
driverString := base64Captcha.DriverString{
Height: int(req.Height), //高度
Width: int(req.Width), //宽度
NoiseCount: 0, //干扰数
ShowLineOptions: 2 | 4, //展示个数
Length: int(req.Length), //长度
Source: "1234567890qwertyuioplkjhgfdsazxcvbnm", //验证码随机字符串来源
BgColor: &color.RGBA{ // 背景颜色
R: 3,
G: 102,
B: 214,
A: 125,
},
Fonts: []string{"wqy-microhei.ttc"}, // 字体
}
driver = driverString.ConvertFonts()
//生成验证码
c := base64Captcha.NewCaptcha(driver, store)
id, b64s, err := c.Generate()
//把生成的验证码id,base64编码赋值给返回的rsp参数
rsp.Id = id
rsp.B64S = b64s
return err
}
//校验验证码的方法
func (e *Captcha) VerifyCaptcha(ctx context.Context, req *pb.VerifyCaptchaRequest, rsp *pb.VerifyCaptchaResponse) error {
// 参数说明: id 验证码id, verifyValue 验证码的值, true: 验证成功后是否删除原来的验证码
if store.Verify(req.Id, req.VerifyValue, true) {
rsp.VerifyResult = true //校验成功
} else {
rsp.VerifyResult = false //校验失败
}
return nil
}
-
Registration Verification Code Microservice Server to Service Discovery (consul)
Run go run main.go in the captcha directory, and then check in the consul UI to see if the registration is successful
![](https://img-blog.csdnimg.cn/img_convert/724aac85e066b4e15cc3582d0c88c2cb.png)
![](https://img-blog.csdnimg.cn/img_convert/8fe589c891b4ba15c383e98cbc8e55ce.png)
Registered successfully
3. Create captcha verification code microservice client
-
Generate client code in the single architecture of the previous mall project
The interface code for calling the captcha verification code in the single-architecture mall is accessed through the interface http://127.0.0.1:8080/admin/captcha . The specific code is as follows:
adminRouters.go
//验证码
adminRouters.GET("/captcha", admin.LoginController{}.Captcha)
LoginController.go
//获取验证码,验证验证码func(con LoginController) Captcha(c *gin.Context) {
id, b64s, err := models.MakeCaptcha(50, 100 ,1)
if err != nil {
fmt.Println(err)
}
c.JSON(http.StatusOK, gin.H{
"captchaId": id,
"captchaImage": b64s,
})
}
The above calls the method MakeCaptcha() in captcha.go under models to obtain the verification code. This captcha.go is also the captcha.go code in 1. Captcha verification code function introduction . This is the original single architecture approach . The access is as follows:
![](https://img-blog.csdnimg.cn/img_convert/590a0851ea99e7146f3724c305c00f19.png)
Now it will be handed over to the captcha verification code microservice to handle
-
First copy the server/captcha/proto folder to the project
![](https://img-blog.csdnimg.cn/6dd9d7ba9dee4fe7ab697e927660811a.png)
-
Encapsulate captcha.go verification code microservice client method
For the verification code in the previous chapters, both the front end and the background need to perform verification code logic processing , and the calling method is the method under models/captcha.go, so when processing the microservice client, it is also modified here
(1). Configure consul service discovery
First, create initCaptchaConsul.go under models, and configure consul service discovery for calling. The code is as follows:
package models
//微服务客户端配置: 初始化consul配置,当一个项目中多个微服务时,就很方便了
//建议:一个微服务对应一个客户端,这样好管理
import (
"github.com/go-micro/plugins/v4/registry/consul"
"go-micro.dev/v4/client"
"go-micro.dev/v4/registry"
)
//CaptchaClient: 全局变量 在外部的包中可以调用
var CaptchaClient client.Client
//init 方法: 当程序运行时就会自动执行
func init() {
consulRegistry := consul.NewRegistry(
//指定微服务的ip: 选择注册服务器地址,默认为本机,也可以选择consul集群中的client,建议一个微服务对应一个consul集群的client
registry.Addrs("127.0.0.1:8500"),
)
// Create service
srv := micro.NewService(
micro.Registry(consulRegistry),
)
srv.Init()
CaptchaClient = srv.Client()
}
Here, maybe not introduced, execute the command: go mod tidy imports the corresponding package
(2). Improve the MakeCaptcha in models/captcha.go to obtain the verification code method
In this method, implement the logic function of calling and obtaining the verification code microservice
//调用获取验证码微服务
func MakeCaptcha(height int, width int, length int) (string, string, error) {
// Create client: 这里的服务名称需要和服务端注册的名称一致
captchaClient := pbCaptcha.NewCaptchaService("captcha", CaptchaClient)
// Call service: 创建连接captcha微服务的连接,并传递参数,
//该方法最终是请求server端handler中的captcha.go中的MakeCaptcha方法
rsp, err := captchaClient.MakeCaptcha(context.Background(), &pbCaptcha.MakeCaptchaRequest{
Height: int32(height), //验证码高度
Width: int32(width), //验证码宽度
Length: int32(length), //验证码长度
})
//判断是否获取成功
if err != nil {
log.Fatal(err)
}
//记录log
log.Info(rsp)
//返回
return rsp.Id, rsp.B64S, err
}
(3). Improve the VerifyCaptcha verification code method in models/captcha.go
In this method, the microservice logic function of calling the verification verification code is realized
//调用校验验证码微服务
func VerifyCaptcha(id string, VerifyValue string) bool {
// Create client: 这里的服务名称需要和服务端注册的名称一致
captchaClient := pbCaptcha.NewCaptchaService("captcha", CaptchaClient)
// Call service: 创建连接captcha微服务的连接,并传递参数,
//该方法最终是请求server端handler中的captcha.go中的VerifyCaptcha方法
rsp, err := captchaClient.VerifyCaptcha(context.Background(), &pbCaptcha.VerifyCaptchaRequest{
Id: id, //验证码Id
VerifyValue: VerifyValue, //验证码
})
//判断是否获取成功
if err != nil {
log.Fatal(err)
}
//记录log
log.Info(rsp)
//返回
return rsp.VerifyResult
}
(4). The complete code is as follows
package models
//验证码属性: https://captcha.mojotv.cn/
import (
"context"
"github.com/prometheus/common/log"
pbCaptcha "goshop/proto/captcha"
)
//调用获取验证码微服务
func MakeCaptcha(height int, width int, length int) (string, string, error) {
// Create client: 这里的服务名称需要和服务端注册的名称一致
captchaClient := pbCaptcha.NewCaptchaService("captcha", CaptchaClient)
// Call service: 创建连接captcha微服务的连接,并传递参数,
//该方法最终是请求server端handler中的captcha.go中的MakeCaptcha方法
rsp, err := captchaClient.MakeCaptcha(context.Background(), &pbCaptcha.MakeCaptchaRequest{
Height: int32(height), //验证码高度
Width: int32(width), //验证码宽度
Length: int32(length), //验证码长度
})
//判断是否获取成功
if err != nil {
log.Fatal(err)
}
//记录log
log.Info(rsp)
//返回
return rsp.Id, rsp.B64S, err
}
//调用校验验证码微服务
func VerifyCaptcha(id string, VerifyValue string) bool {
// Create client: 这里的服务名称需要和服务端注册的名称一致
captchaClient := pbCaptcha.NewCaptchaService("captcha", CaptchaClient)
// Call service: 创建连接captcha微服务的连接,并传递参数,
//该方法最终是请求server端handler中的captcha.go中的VerifyCaptcha方法
rsp, err := captchaClient.VerifyCaptcha(context.Background(), &pbCaptcha.VerifyCaptchaRequest{
Id: id, //验证码Id
VerifyValue: VerifyValue, //验证码
})
//判断是否获取成功
if err != nil {
log.Fatal(err)
}
//记录log
log.Info(rsp)
//返回
return rsp.VerifyResult
}
-
Verify captcha verification code microservice function
(1). Start the server first
see previous code
(2). Start the client
Run in the project root directory : go run main.go to start the project
(3). Visit http://127.0.0.1:8080/admin/captcha
Visit http://127.0.0.1:8080/admin/captcha to see if the verification code related data is displayed
![](https://img-blog.csdnimg.cn/img_convert/bfd7ea8575d458cb855eef4565db409f.png)
It is displayed, indicating that the verification code microservice operation is called
(4). Verify whether the verification code microservice operation is successful
Visit the background login page, enter the user name, password, verification code, and see if it is successful
![](https://img-blog.csdnimg.cn/img_convert/54ca0c0aeddbd3c03587caeb42d06803.png)
![](https://img-blog.csdnimg.cn/img_convert/82d4e7b67d2a92869616200fd7f03f2e.png)
Well, the captcha verification code microservice client operation is completed. Here, the above is the function of calling the captcha verification code microservice on the web page. The following is the explanation of Go Web Restfull APi calling the Captcha verification code microservice
4. Go Web Restfull APi calls Captcha verification code microservice
Go Web Restfull APi calls the Captcha verification code microservice mainly to provide interfaces for mobile apps, WeChat applets, etc. The architecture is as follows
![](https://img-blog.csdnimg.cn/img_convert/74c9ddbd2e7883d641bd70e7bc02080f.png)
-
Create an api Gin project and configure routers
Here directly take the above project as a case, create apiRouters.go routing file under routers
![](https://img-blog.csdnimg.cn/img_convert/fc64cea9bbd697a505842abfdd325c9c.png)
-
Build the verification code related interface, the code is as follows
Write and obtain the verification code under controllers/api/ CaptchaController.go , and verify the relevant logic of the verification code. The code is as follows:
package api
import (
"context"
"github.com/gin-gonic/gin"
"github.com/prometheus/common/log"
"goshop/models"
pbCaptcha "goshop/proto/captcha"
"net/http"
)
type CatpchaController struct {
}
//获取验证码的接口(调用验证码微服务操作)
func (con CatpchaController) MakeCaptcha(c *gin.Context) {
// Create client: 这里的服务名称需要和服务端注册的名称一致
captchaClient := pbCaptcha.NewCaptchaService("captcha", models.CaptchaClient)
// Call service: 创建连接captcha微服务的连接,并传递参数,
//该方法最终是请求server端handler中的captcha.go中的MakeCaptcha方法
rsp, err := captchaClient.MakeCaptcha(context.Background(), &pbCaptcha.MakeCaptchaRequest{
Height: 100, //验证码高度
Width: 200, //验证码宽度
Length: 4, //验证码长度
})
//判断是否获取成功
if err != nil {
log.Fatal(err)
}
//记录log
log.Info(rsp)
//返回
c.JSON(http.StatusOK, gin.H{
"captchaId": rsp.Id,
"B64s": rsp.B64S,
})
}
//校验验证码接口
func (con CatpchaController) VerifyCaptcha(c *gin.Context) {
//获取请求参数
verifyId := c.PostForm("verifyId")
verifyValue := c.PostForm("verifyValue")
// Create client: 这里的服务名称需要和服务端注册的名称一致
captchaClient := pbCaptcha.NewCaptchaService("captcha", models.CaptchaClient)
// Call service: 创建连接captcha微服务的连接,并传递参数,
//该方法最终是请求server端handler中的captcha.go中的VerifyCaptcha方法
rsp, err := captchaClient.VerifyCaptcha(context.Background(), &pbCaptcha.VerifyCaptchaRequest{
Id: verifyId, //验证码Id
VerifyValue: verifyValue, //验证码
})
//判断是否获取成功
if err != nil {
log.Fatal(err)
}
//记录log
log.Info(rsp)
//返回
if rsp.VerifyResult == true { // 说明验证通过
c.JSON(http.StatusOK, gin.H{
"message": "验证验证码成功",
"success": true,
})
} else {
c.JSON(http.StatusOK, gin.H{
"message": "验证验证码失败",
"success": false,
})
}
}
-
Check whether the api request is successful
Request http://127.0.0.1:8080/api/MakeCaptcha to see if the corresponding verification code json request is returned
![](https://img-blog.csdnimg.cn/img_convert/cd0c5a70c0b19e07656276476cad14b7.png)
As can be seen from the above figure, if the data corresponding to the verification code is returned, put the data in B64s into <img src = "B64s" />, and it will be fine. The displayed picture is as follows:
![](https://img-blog.csdnimg.cn/img_convert/6540c07f691aaa3df4ab8083a0be525e.png)
Then verify the verification code, usually through postman verification
![](https://img-blog.csdnimg.cn/img_convert/57a89a899894d60f20d39f5c84fde3b5.png)
Well, the Go Web Restfull APi calls the Captcha verification code microservice to obtain the verification code, and the operation of verifying the verification code api interface is completed
[Previous section] [golang gin framework] 39. Gin Mall Project - Microservice Architecture in Microservice Practice