encoding.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. *
  3. * Copyright 2017 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. // Package encoding defines the interface for the compressor and the functions
  19. // to register and get the compossor.
  20. // This package is EXPERIMENTAL.
  21. package encoding
  22. import (
  23. "io"
  24. )
  25. var registerCompressor = make(map[string]Compressor)
  26. // Compressor is used for compressing and decompressing when sending or receiving messages.
  27. type Compressor interface {
  28. // Compress writes the data written to wc to w after compressing it. If an error
  29. // occurs while initializing the compressor, that error is returned instead.
  30. Compress(w io.Writer) (io.WriteCloser, error)
  31. // Decompress reads data from r, decompresses it, and provides the uncompressed data
  32. // via the returned io.Reader. If an error occurs while initializing the decompressor, that error
  33. // is returned instead.
  34. Decompress(r io.Reader) (io.Reader, error)
  35. // Name is the name of the compression codec and is used to set the content coding header.
  36. Name() string
  37. }
  38. // RegisterCompressor registers the compressor with gRPC by its name. It can be activated when
  39. // sending an RPC via grpc.UseCompressor(). It will be automatically accessed when receiving a
  40. // message based on the content coding header. Servers also use it to send a response with the
  41. // same encoding as the request.
  42. //
  43. // NOTE: this function must only be called during initialization time (i.e. in an init() function). If
  44. // multiple Compressors are registered with the same name, the one registered last will take effect.
  45. func RegisterCompressor(c Compressor) {
  46. registerCompressor[c.Name()] = c
  47. }
  48. // GetCompressor returns Compressor for the given compressor name.
  49. func GetCompressor(name string) Compressor {
  50. return registerCompressor[name]
  51. }
  52. // Identity specifies the optional encoding for uncompressed streams.
  53. // It is intended for grpc internal use only.
  54. const Identity = "identity"