|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "log" |
| 7 | + "time" |
| 8 | + |
| 9 | + "go_client/pb" |
| 10 | + |
| 11 | + "google.golang.org/grpc" |
| 12 | + "google.golang.org/grpc/credentials/insecure" |
| 13 | + "google.golang.org/protobuf/proto" |
| 14 | + "google.golang.org/protobuf/types/known/wrapperspb" |
| 15 | +) |
| 16 | + |
| 17 | +func main() { |
| 18 | + // Connect to the Java gRPC server |
| 19 | + addr := "localhost:8080" |
| 20 | + conn, err := grpc.Dial(addr, grpc.WithTransportCredentials(insecure.NewCredentials())) |
| 21 | + if err != nil { |
| 22 | + log.Fatalf("did not connect: %v", err) |
| 23 | + } |
| 24 | + defer conn.Close() |
| 25 | + |
| 26 | + client := pb.NewGrpcServiceClient(conn) |
| 27 | + |
| 28 | + // Wrap the parameter in a Protobuf StringValue |
| 29 | + param := wrapperspb.String( "World") |
| 30 | + paramBytes, err := proto.Marshal(param) |
| 31 | + if err != nil { |
| 32 | + log.Fatalf("failed to marshal param: %v", err) |
| 33 | + } |
| 34 | + |
| 35 | + // Prepare the RPC request |
| 36 | + req := &pb.RpcRequest{ |
| 37 | + InterfaceName: "com.xiaoyu.rpc.api.HelloService", |
| 38 | + MethodName: "sayHello", |
| 39 | + ParamTypes: []string{"java.lang.String"}, |
| 40 | + Parameters: [][]byte{paramBytes}, |
| 41 | + RequestId: fmt.Sprintf("go-req-%d", time.Now().UnixNano()), |
| 42 | + } |
| 43 | + |
| 44 | + // Set a timeout for the call |
| 45 | + ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) |
| 46 | + defer cancel() |
| 47 | + |
| 48 | + // Call the handle method |
| 49 | + fmt.Printf("Sending RpcRequest: interface=%s, method=%s, param=%s\n", req.InterfaceName, req.MethodName, "World") |
| 50 | + resp, err := client.Handle(ctx, req) |
| 51 | + if err != nil { |
| 52 | + log.Fatalf("could not call handle: %v", err) |
| 53 | + } |
| 54 | + |
| 55 | + fmt.Println("RpcResponse received:") |
| 56 | + if resp.Message == "Success" { |
| 57 | + resultVal := &wrapperspb.StringValue{} |
| 58 | + if err := proto.Unmarshal(resp.Data, resultVal); err != nil { |
| 59 | + log.Printf("failed to unmarshal data: %v", err) |
| 60 | + fmt.Printf("Data (Raw): %v\n", resp.Data) |
| 61 | + } else { |
| 62 | + fmt.Printf("Data: %s\n", resultVal.Value) |
| 63 | + } |
| 64 | + } else { |
| 65 | + fmt.Printf("Data (Raw): %v\n", resp.Data) |
| 66 | + } |
| 67 | + fmt.Printf("Message: %s\n", resp.Message) |
| 68 | + fmt.Printf("RequestID: %s\n", resp.RequestId) |
| 69 | +} |
0 commit comments