问题描述
我是 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
}
Calculator.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。请帮帮我。寻求某种帮助或提示。
解决方法
实际上我应该使用 setParam1 和 setParam2 来设置如下值:
let calculate = function (client,param1,param2) {
return new Promise(function (resolve,reject) {
try {
let additionRequest = new AdditionRequest();
additionRequest.setParam1(param1);
additionRequest.setParam2(param2);
client.add(additionRequest,null,function (err,response) {
let pong = response.toObject();
resolve(pong);
});
} catch (e) {
reject(e);
}
});
};