compress.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. package sumologicexporter // import "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/sumologicexporter"
  4. import (
  5. "bytes"
  6. "compress/flate"
  7. "compress/gzip"
  8. "fmt"
  9. "io"
  10. )
  11. type compressor struct {
  12. format CompressEncodingType
  13. writer encoder
  14. buf bytes.Buffer
  15. }
  16. type encoder interface {
  17. io.WriteCloser
  18. Reset(dst io.Writer)
  19. }
  20. // newCompressor takes encoding format and returns compressor struct and error eventually
  21. func newCompressor(format CompressEncodingType) (compressor, error) {
  22. var (
  23. writer encoder
  24. err error
  25. )
  26. switch format {
  27. case GZIPCompression:
  28. writer = gzip.NewWriter(io.Discard)
  29. case DeflateCompression:
  30. writer, err = flate.NewWriter(io.Discard, flate.BestSpeed)
  31. if err != nil {
  32. return compressor{}, err
  33. }
  34. case NoCompression:
  35. writer = nil
  36. default:
  37. return compressor{}, fmt.Errorf("invalid format: %s", format)
  38. }
  39. return compressor{
  40. format: format,
  41. writer: writer,
  42. }, nil
  43. }
  44. // compress takes a reader with uncompressed data and returns
  45. // a reader with the same data compressed using c.writer
  46. func (c *compressor) compress(data io.Reader) (io.Reader, error) {
  47. if c.writer == nil {
  48. return data, nil
  49. }
  50. var dataBytes bytes.Buffer
  51. if _, err := dataBytes.ReadFrom(data); err != nil {
  52. return nil, err
  53. }
  54. // Reset c.buf to start with empty message
  55. c.buf.Reset()
  56. c.writer.Reset(&c.buf)
  57. if _, err := c.writer.Write(dataBytes.Bytes()); err != nil {
  58. return nil, err
  59. }
  60. if err := c.writer.Close(); err != nil {
  61. return nil, err
  62. }
  63. return bytes.NewReader(c.buf.Bytes()), nil
  64. }