I am a beginner in golang and GRPC. I am trying to use React as frontend , GRPC instead of API and GoLang as backend. I am just trying to pass two int64 parameter in add() service and return the sum but the parameter is always 0 when i try to log in server.
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);
});
Output in server console
2021/04/25 13:04:08 Get Param1:
2021/04/25 13:04:08 0
Output in browser console
Even i have sent parameters i.e 10 and 20, i get 0 in server side. Please help me guys. Looking for somekind of help or hints.
Actually i should have used setParam1 & setParam2 to set values like below:
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);
}
});
};