用戶登錄
介紹了如何使用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 stringvar pbData *pb.LoginResponseif 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專欄