github.com/newrelic/newrelic-client-go@v1.1.0/internal/http/compress.go (about)

     1  package http
     2  
     3  import (
     4  	"bufio"
     5  	"bytes"
     6  	"compress/gzip"
     7  	"io"
     8  )
     9  
    10  const (
    11  	// CompressorMinimumSize is the required size in bytes that a body exceeds before it is compressed
    12  	CompressorMinimumSize = 150
    13  )
    14  
    15  type RequestCompressor interface {
    16  	Compress(r *Request, body []byte) (io.Reader, error)
    17  }
    18  
    19  // NoneCompressor does not compress the request at all.
    20  type NoneCompressor struct{}
    21  
    22  // CompressRequest returns a reader for the body to the caller
    23  func (c *NoneCompressor) Compress(r *Request, body []byte) (io.Reader, error) {
    24  	buffer := bytes.NewBuffer(body)
    25  	r.DelHeader("Content-Encoding")
    26  
    27  	return buffer, nil
    28  }
    29  
    30  // GzipCompressor compresses the body with gzip
    31  type GzipCompressor struct{}
    32  
    33  // CompressRequest gzips the body, sets the content encoding header, and returns a reader to the caller
    34  func (c *GzipCompressor) Compress(r *Request, body []byte) (io.Reader, error) {
    35  	var err error
    36  
    37  	// Adaptive compression
    38  	if len(body) < CompressorMinimumSize {
    39  		buf := bytes.NewBuffer(body)
    40  		r.DelHeader("Content-Encoding")
    41  
    42  		return buf, nil
    43  	}
    44  
    45  	readBuffer := bufio.NewReader(bytes.NewReader(body))
    46  	buffer := bytes.NewBuffer([]byte{})
    47  	writer := gzip.NewWriter(buffer)
    48  
    49  	_, err = readBuffer.WriteTo(writer)
    50  	if err != nil {
    51  		return nil, err
    52  	}
    53  
    54  	err = writer.Close()
    55  	if err != nil {
    56  		return nil, err
    57  	}
    58  
    59  	r.SetHeader("Content-Encoding", "gzip")
    60  
    61  	return buffer, nil
    62  }