github.com/philippseith/signalr@v0.6.3/chatsample/middleware/response_writer_wrapper.go (about)

     1  package middleware
     2  
     3  import (
     4  	"bufio"
     5  	"errors"
     6  	"net"
     7  	"net/http"
     8  )
     9  
    10  func wrapResponseWriter(w http.ResponseWriter) *responseWriterWrapper {
    11  	return &responseWriterWrapper{ResponseWriter: w}
    12  }
    13  
    14  // responseWriterWrapper is a minimal wrapper for http.ResponseWriter that allows the
    15  // written HTTP status code to be captured for logging.
    16  // adapted from: https://github.com/elithrar/admission-control/blob/df0c4bf37a96d159d9181a71cee6e5485d5a50a9/request_logger.go#L11-L13
    17  type responseWriterWrapper struct {
    18  	http.ResponseWriter
    19  	status      int
    20  	wroteHeader bool
    21  }
    22  
    23  // Status provides access to the wrapped http.ResponseWriter's status
    24  func (rw *responseWriterWrapper) Status() int {
    25  	return rw.status
    26  }
    27  
    28  // Header provides access to the wrapped http.ResponseWriter's header
    29  // allowing handlers to set HTTP headers on the wrapped response
    30  func (rw *responseWriterWrapper) Header() http.Header {
    31  	return rw.ResponseWriter.Header()
    32  }
    33  
    34  // WriteHeader intercepts the written status code and caches it
    35  // so that we can access it later
    36  func (rw *responseWriterWrapper) WriteHeader(code int) {
    37  	if rw.wroteHeader {
    38  		return
    39  	}
    40  
    41  	rw.status = code
    42  	rw.ResponseWriter.WriteHeader(code)
    43  	rw.wroteHeader = true
    44  
    45  	return
    46  }
    47  
    48  // Flush implements http.Flusher
    49  func (rw *responseWriterWrapper) Flush() {
    50  	if flusher, ok := rw.ResponseWriter.(http.Flusher); ok {
    51  		flusher.Flush()
    52  	}
    53  }
    54  
    55  func (rw *responseWriterWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) {
    56  	if hijacker, ok := rw.ResponseWriter.(http.Hijacker); ok {
    57  		return hijacker.Hijack()
    58  	}
    59  	return nil, nil, errors.New("http.Hijacker not implemented")
    60  }