go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/iotools/responsewriter.go (about)

     1  // Copyright 2019 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package iotools
    16  
    17  import (
    18  	"net/http"
    19  )
    20  
    21  // ResponseWriter wraps a given http.ResponseWriter, records its status code and
    22  // response size.
    23  //
    24  // Assumes all writes are externally synchronized.
    25  type ResponseWriter struct {
    26  	rw     http.ResponseWriter
    27  	writer CountingWriter
    28  	status int
    29  }
    30  
    31  // NewResponseWriter constructs a ResponseWriter that wraps given 'rw' and
    32  // tracks how much data was written to it and what status code was set.
    33  func NewResponseWriter(rw http.ResponseWriter) *ResponseWriter {
    34  	return &ResponseWriter{
    35  		rw:     rw,
    36  		writer: CountingWriter{Writer: rw},
    37  		status: http.StatusOK,
    38  	}
    39  }
    40  
    41  // ResponseSize is size of the response body written so far.
    42  func (rw *ResponseWriter) ResponseSize() int64 { return rw.writer.Count }
    43  
    44  // Status is the HTTP status code set in the response.
    45  func (rw *ResponseWriter) Status() int { return rw.status }
    46  
    47  // http.ResponseWriter interface.
    48  
    49  // Header returns the header map that will be sent by WriteHeader.
    50  func (rw *ResponseWriter) Header() http.Header { return rw.rw.Header() }
    51  
    52  // Write writes the data to the connection as part of an HTTP reply.
    53  func (rw *ResponseWriter) Write(buf []byte) (int, error) { return rw.writer.Write(buf) }
    54  
    55  // WriteHeader sends an HTTP response header with the provided status code.
    56  func (rw *ResponseWriter) WriteHeader(code int) {
    57  	rw.status = code
    58  	rw.rw.WriteHeader(code)
    59  }
    60  
    61  // http.Flusher interface.
    62  
    63  // Flush sends any buffered data to the client.
    64  func (rw *ResponseWriter) Flush() {
    65  	if f, ok := rw.rw.(http.Flusher); ok {
    66  		f.Flush()
    67  	}
    68  }