grpc:服务器无法编码响应:rpc错误:代码=内部desc = grpc:编组时出错:原型:元帅以nil调用

时间:2018-08-12 08:26:09

标签: go grpc

理想情况下,以下RPC应该会收到一条消息并封送至JSON。但是,遇到以下错误:ERROR: 2018/08/12 13:43:07 grpc: server failed to encode response: rpc error: code = Internal desc = grpc: error while marshaling: proto: Marshal called with nil

func (s *beaconServer) Transmit(ctx context.Context, batch *pb.Batch) (*pb.Empty, error) {
    var empty *pb.Empty

    var messageJSON bytes.Buffer
    marshaler := &jsonpb.Marshaler{
        OrigName: true,
    }
    err := marshaler.Marshal(&messageJSON, batch)
    if err != nil {
        return empty, err
    }

    log.Println(string(messageJSON.Bytes()))
    return empty, nil
}

..返回

2018/08/12 14:24:09 beacon.go:34: {"stream_id":"abc11","event_type":"e","events":[{"file_path":"/tmp/python.py","location":"256","count":"30"},{"file_path":"/tmp/temp.py","location":"253","count":"305"}],"start_time":"2038-01-19 03:14:07","end_time":"2038-01-19 03:14:27"}
ERROR: 2018/08/12 14:24:09 grpc: server failed to encode response:  rpc error: code = Internal desc = grpc: error while marshaling: proto: Marshal called with nil

1 个答案:

答案 0 :(得分:3)

该错误可能不是由此代码块中的编组引起的

当您执行var empty *pb.Empty时,您正在创建一个未初始化的变量*pb.Empty,它是nil。很有可能是上游某个试图封送此empty的东西引起了错误。

此处为可运行示例: https://play.golang.org/p/QsNCWXM615Q

如果要初始化为空,则应执行return new(pb.Empty), nil