golang游戏服务器 - tgf系列课程04

用户登录

介绍了如何使用tgf自带的登录功能进行用户的登录操作,并且编写机器人客户端的一个模拟请求代码

需求描述

用户请求登录,登录成功之后请求HelloWorld接口.

Common

接口定义和生成
接口定义
新增登录接口
type IHallService interface {
	Login(ctx context.Context, args *rpc.Args[*pb.LoginRequest], reply *rpc.Reply[*pb.LoginResponse]) (err error)
	HelloWorld(ctx context.Context, args *rpc.Args[*pb.HelloWorldRequest], reply *rpc.Reply[*pb.HelloWorldResponse]) (err error)
}
生成api文件
查看 项目文档,在kit项目中创建生成api接口文件脚本
func main() {
	//设置导出的golang目录
	util.SetAutoGenerateAPICodePath("../common/api")
	//根据接口生成对应的api结构
	util.GeneratorAPI[services.IHallService](hall.ModuleName, hall.Version, "api")
}

Service

逻辑端
完善接口逻辑
使用 rpc.UserLogin函数登录
func (s *service) Login(ctx context.Context, args *rpc.Args[*pb.LoginRequest], reply *rpc.Reply[*pb.LoginResponse]) (err error) {
	var userId string
	var pbData *pb.LoginResponse
	if args.GetData().GetAccount() == "admin" && args.GetData().GetPassword() == "123" {
		userId = util.GenerateSnowflakeId()
		rpc.UserLogin(ctx, userId)
		pbData = &pb.LoginResponse{Success: true}
	} else {
		pbData = &pb.LoginResponse{Success: false}
	}
	reply.SetData(pbData)
	return
}

Robot

请求代码
监听登录和HelloWorld接口的回调,并发起请求
func TestHelloWorld(t *testing.T) {
	rb := CreateRobot()
	rb.RegisterCallbackMessage(api.HelloWorld.MessageType, func(i robot.IRobot, bytes []byte) {
		resp := &pb.HelloWorldResponse{}
		proto.Unmarshal(bytes, resp)
		t.Log(resp.Message)
	}).RegisterCallbackMessage(api.Login.MessageType, func(i robot.IRobot, bytes []byte) {
		resp := &pb.LoginResponse{}
		proto.Unmarshal(bytes, resp)
		if resp.Success {
			i.Send(api.HelloWorld.MessageType, &pb.HelloWorldRequest{Name: "tgf"})
		} else {
			t.Log("login fail")
		}
	})
	//
	rb.Send(api.Login.MessageType, &pb.LoginRequest{
		Account:  "admin",
		Password: "123",
	})
	select {}
}

交流群

QQ群:7400585

下期预告

逻辑节点间的rpc调用

视频教程

golang游戏服务器 - tgf系列课程04
B站教程合集

项目地址

项目地址
项目案例
项目文档
知乎博客
CSDN专栏

  • 13
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值