实现:grpc内部代码实现!

recvCompress: req.Header.Get(“grpc-encoding”),
headerFields = append(headerFields, hpack.HeaderField{Name: “grpc-encoding”, Value: s.sendCompress})

stream 内有:
recvCompress string
sendCompress string

使用:

res, err := c.UnaryEcho(ctx, &pb.EchoRequest{Message: msg}, grpc.UseCompressor(gzip.Name))
!

grpc 代码实现;

  1. if rc := stream.RecvCompress(); s.opts.dc != nil && s.opts.dc.Type() == rc {
  2. dc = s.opts.dc
  3. } else if rc != "" && rc != encoding.Identity {
  4. decomp = encoding.GetCompressor(rc)
  5. if decomp == nil {
  6. st := status.Newf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", rc)
  7. t.WriteStatus(stream, st)
  8. return st.Err()
  9. }
  10. }
  11. // If cp is set, use it. Otherwise, attempt to compress the response using
  12. // the incoming message compression method.
  13. //
  14. // NOTE: this needs to be ahead of all handling, https://github.com/grpc/grpc-go/issues/686.
  15. if s.opts.cp != nil {
  16. cp = s.opts.cp
  17. stream.SetSendCompress(cp.Type())
  18. } else if rc := stream.RecvCompress(); rc != "" && rc != encoding.Identity {
  19. // Legacy compressor not specified; attempt to respond with same encoding.
  20. comp = encoding.GetCompressor(rc)
  21. if comp != nil {
  22. stream.SetSendCompress(rc)
  23. }
  24. }