【发布时间】:2021-04-25 07:37:09
【问题描述】:
我是 golang 和 GRPC 的初学者。我正在尝试使用 React 作为前端、GRPC 而不是 API 和 GoLang 作为后端。 我只是想在 add() 服务中传递两个 int64 参数并返回总和,但是当我尝试登录服务器时参数始终为 0。
service.proto
syntax = "proto3";
package main;
option go_package="./pingpong";
message PingRequest {
}
message PongResponse {
bool ok = 1;
}
message AdditionRequest {
int64 param1 = 2;
int64 param2 = 3;
}
message AdditionResponse {
int64 output = 4;
}
service PingPong{
rpc Ping(PingRequest) returns (PongResponse) {};
rpc Add(AdditionRequest) returns (AdditionResponse) {};
}
server.go
package handler
import (
"context"
"log"
"github.com/sibesh/react-go/pingpong"
)
// Server is the Logic handler for the server
// It has to fullfill the GRPC schema generated Interface
// In this case its only 1 function called Ping
type Server struct {
pingpong.UnimplementedPingPongServer
}
// Ping fullfills the requirement for PingPong Server interface
func (s *Server) Ping(ctx context.Context, ping *pingpong.PingRequest) (*pingpong.PongResponse, error) {
log.Println("Server Requested")
return &pingpong.PongResponse{
Ok: true,
}, nil
}
// Ping fullfills the requirement for PingPong Server interface
func (s *Server) Add(ctx context.Context, request *pingpong.AdditionRequest) (*pingpong.AdditionResponse, error) {
output := request.GetParam1() + request.GetParam2()
log.Println("Get Param1: ")
log.Println(request.GetParam1())
return &pingpong.AdditionResponse{
Output: output,
}, nil
}
计算器.js
let calculate = function (client, param1, param2) {
return new Promise(function (resolve, reject) {
try {
let additionRequest = new AdditionRequest(param1, param2);
client.add(additionRequest, null, function (err, response) {
let pong = response.toObject();
resolve(pong);
});
} catch (e) {
reject(e);
}
});
};
calculate(this.client, this.state.param1, this.state.param2)
.then((results) => {
console.log(results);
this.setState(results);
this.forceUpdate();
})
.catch((error) => {
console.log(error);
});
服务器控制台输出
2021/04/25 13:04:08 Get Param1:
2021/04/25 13:04:08 0
在浏览器控制台中输出
即使我发送了参数,即 10 和 20,我在服务器端得到 0。请帮帮我。寻求某种帮助或提示。
【问题讨论】:
-
你在使用 grpc-web 客户端吗? github.com/grpc/grpc-web
-
是的,我已经在使用它了。我也得到了服务器响应,但参数未正确获取 @Shaikhul
-
AdditionRequest是 protobuf 请求还是您的自定义函数?您在什么时候为请求设置参数(例如 setParam1 和 setParam2)?