登录接口,筹划利用 grpc 作为接口规范。
一、服务端生成 typescript 版 grpc 接口文件
1. 创建 auth.proto
syntax = "proto3";option go_package = "proto/auth";service Auth { rpc AuthLogin (AuthRequestLogin) returns (AuthReplyLogin) {};}// 登录message AuthRequestLogin { string account = 1; string enPassword = 2;}message AuthReplyLogin { uint32 code = 1; string content = 2; uint64 count = 3; Msg msg = 4;}message Msg { string success = 1; string fail = 2;}2. 生成Go 客户端代码
protoc -I="." --go_out=./proto/output ./proto/auth/*.proto protoc -I="." --go-grpc_out=./proto/output ./proto/auth/*.proto 3. 生成 typescript 客户端代码
protoc -I="." --js_out=import_style=commonjs:./proto/output --grpc-web_out=import_style=typescript,mode=grpcwebtext:./proto/output ./proto/auth/*.proto4. go 客户端测试代码
func TestGrpcAuth(t *testing.T) { credentials := insecure.NewCredentials() conn, _ := grpc.Dial("127.0.0.1:2022", grpc.WithTransportCredentials(credentials), grpc.WithBlock()) defer conn.Close() client := auth.NewAuthClient(conn) resp, err := client.AuthLogin(context.Background(), &auth.AuthRequestLogin{ Account: "admin", EnPassword: "Y7/438TPNn59zoWiBqnGxVNd4eeivbhC0F9NA/OoKhwz1lHDMNU6L6unFiPGcHHGMQRq+pX8xYIssC5U6GxGZQEz4l2yPgZMCHC6ZaG1lfBTsBOjv0TWFqr03rTi0iqrdF2/Zi8S4CXnh3NCfLKBooJlNO8G9FlOAMWonuqTUE=", }) if err != nil { t.Error(err) } t.Log(resp)}
5. typescript 客户端测试代码
接入前端代码之前必要先启动一个grpc web署理:
./bin/grpcwebproxy-v0.15.0-win64.exe --allow_all_origins --backend_addr=localhost:2022 --run_tls_server=false --server_http_debug_port=7006
- 2022 是grpc服务端监听端口、7006 是署理端口,前端发送哀求时,利用 7006 端口。
前端测试代码如下:
import * as grpcWeb from 'grpc-web'import {AuthClient} from "./AuthServiceClientPb";import {AuthRequestLogin, AuthReplyLogin} from "./auth_pb";const service = new AuthClient("http://localhost:7006", null, null)const req = new AuthRequestLogin()const resp = new AuthReplyLogin()export function testGrpcAuth() { req.setAccount("admin") req.setEnpassword("Y7/438TPNn59zoWiBqnGVNd4eeivbhC0F9NA/xOoKhwz1lHDMNU6L6unFiPGcHHGMQRq+pX8xYIssC5U6GxGZQEz4l2yPgZMCHC6ZaG1lfBTsBOjv0TWFqr03rTi0iqrdF2/Zi8S4CXnh3NCfLKBooJlNO8G9FlOAMWonuqTUE=") const call = service.authLogin(req, {}, (err: grpcWeb.RpcError, response: AuthReplyLogin) => { if(err) { console.log(err.code) console.log(err.message) } else { console.log("unary resp: ",response) console.log("code:",response.getCode()) console.log("content:",response.getContent()) } }) call.on('status', (status: grpcWeb.Status) => { // console.log('status: ', status) })}
|