github.com/xmidt-org/webpa-common@v1.11.9/health/responseWriter.go (about)

     1  package health
     2  
     3  import (
     4  	"bufio"
     5  	"errors"
     6  	"net"
     7  	"net/http"
     8  )
     9  
    10  // Wrap returns a *health.ResponseWriter which wraps the given
    11  // http.ResponseWriter
    12  func Wrap(delegate http.ResponseWriter) *ResponseWriter {
    13  	return &ResponseWriter{
    14  		ResponseWriter: delegate,
    15  	}
    16  }
    17  
    18  // ResponseWriter is a wrapper type for an http.ResponseWriter that exposes the status code.
    19  type ResponseWriter struct {
    20  	http.ResponseWriter
    21  	statusCode int
    22  }
    23  
    24  func (r *ResponseWriter) StatusCode() int {
    25  	return r.statusCode
    26  }
    27  
    28  func (r *ResponseWriter) WriteHeader(statusCode int) {
    29  	r.statusCode = statusCode
    30  	r.ResponseWriter.WriteHeader(statusCode)
    31  }
    32  
    33  // CloseNotify delegates to the wrapped ResponseWriter, panicking if the delegate does
    34  // not implement http.CloseNotifier.
    35  func (r *ResponseWriter) CloseNotify() <-chan bool {
    36  	if closeNotifier, ok := r.ResponseWriter.(http.CloseNotifier); ok {
    37  		return closeNotifier.CloseNotify()
    38  	}
    39  
    40  	// TODO: Not quite sure what the best thing to do here is.  At least with
    41  	// a panic, we'll catch it later and can decide what to do.
    42  	panic(errors.New("Wrapped response does not implement http.CloseNotifier"))
    43  }
    44  
    45  // Hijack delegates to the wrapped ResponseWriter, returning an error if the delegate does
    46  // not implement http.Hijacker.
    47  func (r *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
    48  	if hijacker, ok := r.ResponseWriter.(http.Hijacker); ok {
    49  		return hijacker.Hijack()
    50  	}
    51  
    52  	return nil, nil, errors.New("Wrapped response does not implement http.Hijacker")
    53  }
    54  
    55  // Flush delegates to the wrapped ResponseWriter.  If the delegate ResponseWriter does not
    56  // implement http.Flusher, this method does nothing.
    57  func (r *ResponseWriter) Flush() {
    58  	if flusher, ok := r.ResponseWriter.(http.Flusher); ok {
    59  		flusher.Flush()
    60  	}
    61  }
    62  
    63  // Push delegates to the wrapper ResponseWriter, returning an error if the delegate does
    64  // not implement http.Pusher.
    65  func (r *ResponseWriter) Push(target string, opts *http.PushOptions) error {
    66  	if pusher, ok := r.ResponseWriter.(http.Pusher); ok {
    67  		return pusher.Push(target, opts)
    68  	}
    69  
    70  	return errors.New("Wrapped response does not implement http.Pusher")
    71  }