727
登录接口,计划使用 grpc 作为接口规范。
auth.protosyntax = "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;}protoc -I="." --go_out=./proto/output ./proto/auth/*.proto protoc -I="." --go-grpc_out=./proto/output ./proto/auth/*.proto
protoc -I="." --js_out=import_style=commonjs:./proto/output --grpc-web_out=import_style=typescript,mode=grpcwebtext:./proto/output ./proto/auth/*.proto

生成结果
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)}属于账号 + 密码 作为接口参数

go 客户端测试通过
接入前端代码之前需要先启动一个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)
})}
前端接口访问
可以看到前端也实现了grpc接口访问
转载来源于七境
1
2
3
4