withcoderesponsewriter.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package security
  2. import (
  3. "bufio"
  4. "net"
  5. "net/http"
  6. )
  7. // A WithCodeResponseWriter is a helper to delay sealing a http.ResponseWriter on writing code.
  8. type WithCodeResponseWriter struct {
  9. Writer http.ResponseWriter
  10. Code int
  11. }
  12. // Flush flushes the response writer.
  13. func (w *WithCodeResponseWriter) Flush() {
  14. if flusher, ok := w.Writer.(http.Flusher); ok {
  15. flusher.Flush()
  16. }
  17. }
  18. // Header returns the http header.
  19. func (w *WithCodeResponseWriter) Header() http.Header {
  20. return w.Writer.Header()
  21. }
  22. // Hijack implements the http.Hijacker interface.
  23. // This expands the Response to fulfill http.Hijacker if the underlying http.ResponseWriter supports it.
  24. func (w *WithCodeResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  25. return w.Writer.(http.Hijacker).Hijack()
  26. }
  27. // Write writes bytes into w.
  28. func (w *WithCodeResponseWriter) Write(bytes []byte) (int, error) {
  29. return w.Writer.Write(bytes)
  30. }
  31. // WriteHeader writes code into w, and not sealing the writer.
  32. func (w *WithCodeResponseWriter) WriteHeader(code int) {
  33. w.Writer.WriteHeader(code)
  34. w.Code = code
  35. }