github.com/blend/go-sdk@v1.20220411.3/webutil/gzip_response_writer.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package webutil
     9  
    10  import (
    11  	"compress/gzip"
    12  	"net/http"
    13  )
    14  
    15  var (
    16  	_ ResponseWriter      = (*GZipResponseWriter)(nil)
    17  	_ http.ResponseWriter = (*GZipResponseWriter)(nil)
    18  	_ http.Flusher        = (*GZipResponseWriter)(nil)
    19  )
    20  
    21  // NewGZipResponseWriter returns a new gzipped response writer.
    22  func NewGZipResponseWriter(w http.ResponseWriter) *GZipResponseWriter {
    23  	if typed, ok := w.(ResponseWriter); ok {
    24  		return &GZipResponseWriter{
    25  			innerResponse: typed.InnerResponse(),
    26  			gzipWriter:    gzip.NewWriter(typed.InnerResponse()),
    27  		}
    28  	}
    29  	return &GZipResponseWriter{
    30  		innerResponse: w,
    31  		gzipWriter:    gzip.NewWriter(w),
    32  	}
    33  }
    34  
    35  // GZipResponseWriter is a response writer that compresses output.
    36  type GZipResponseWriter struct {
    37  	gzipWriter    *gzip.Writer
    38  	innerResponse http.ResponseWriter
    39  	statusCode    int
    40  	contentLength int
    41  }
    42  
    43  // InnerResponse returns the underlying response.
    44  func (crw *GZipResponseWriter) InnerResponse() http.ResponseWriter {
    45  	return crw.innerResponse
    46  }
    47  
    48  // Write writes the byes to the stream.
    49  func (crw *GZipResponseWriter) Write(b []byte) (int, error) {
    50  	_, err := crw.gzipWriter.Write(b)
    51  	crw.contentLength += len(b)
    52  	return len(b), err
    53  }
    54  
    55  // Header returns the headers for the response.
    56  func (crw *GZipResponseWriter) Header() http.Header {
    57  	return crw.innerResponse.Header()
    58  }
    59  
    60  // WriteHeader writes a status code.
    61  func (crw *GZipResponseWriter) WriteHeader(code int) {
    62  	crw.statusCode = code
    63  	crw.innerResponse.WriteHeader(code)
    64  }
    65  
    66  // StatusCode returns the status code for the request.
    67  func (crw *GZipResponseWriter) StatusCode() int {
    68  	return crw.statusCode
    69  }
    70  
    71  // ContentLength returns the content length for the request.
    72  func (crw *GZipResponseWriter) ContentLength() int {
    73  	return crw.contentLength
    74  }
    75  
    76  // Flush pushes any buffered data out to the response.
    77  func (crw *GZipResponseWriter) Flush() {
    78  	crw.gzipWriter.Flush()
    79  }
    80  
    81  // Close closes any underlying resources.
    82  func (crw *GZipResponseWriter) Close() error {
    83  	return crw.gzipWriter.Close()
    84  }