接口:
package main
import (
"context"
"errors"
"google.golang.org/grpc"
"log"
"net"
"testgo/proto"
"testgo/service"
)
const (
port = ":9543"
)
type server struct {
}
func (server) Calculate(ctx context.Context, in *client.Request) (resp *client.Response, e error) {
log.Printf("Received request")
defer func() { // 必须要先声明defer,否则不能捕获到panic异常
if err := recover(); err != nil {
e = errors.New(err.(string)) // 这里的err其实就是panic传入的内容
}
}()
c := service.Calculate{Num1: in.Num1, Num2: in.Num2,}
var result float64
switch in.OpType {
case client.OperateType_Addition:
result = c.Operate(service.Addition)
case client.OperateType_Division:
result = c.Operate(service.Division)
case client.OperateType_Multiplication:
result = c.Operate(service.Multiplication)
case client.OperateType_Subtraction:
result = c.Operate(service.Subtraction)
}
return &client.Response{Result: result,}, nil
}
func main() {
lis, err := net.Listen("tcp", port)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
client.RegisterOperateServer(s, &server{})
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
业务代码:
package service
type Calculate struct {
Num1 float64
Num2 float64
}
type Operate func(num1, num2 float64) (result float64)
//操作接口
func (c Calculate) Operate(op Operate) (result float64) {
return op(c.Num1, c.Num2)
}
package service
//定义操作类型
func Addition(num1, num2 float64) (result float64) {
return num1 + num2
}
func Division(num1, num2 float64) (result float64) {
if num2 == 0 {
panic("division by zero")
}
return num1 / num2
}
func Multiplication(num1, num2 float64) (result float64) {
return num1 * num2
}
func Subtraction(num1, num2 float64) (result float64) {
return num1 - num2
}
如果server端代码有问题的童鞋,可以参考go官方的rpc调用example