writer.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package flushwriter
  14. import (
  15. "io"
  16. "net/http"
  17. )
  18. // Wrap wraps an io.Writer into a writer that flushes after every write if
  19. // the writer implements the Flusher interface.
  20. func Wrap(w io.Writer) io.Writer {
  21. fw := &flushWriter{
  22. writer: w,
  23. }
  24. if flusher, ok := w.(http.Flusher); ok {
  25. fw.flusher = flusher
  26. }
  27. return fw
  28. }
  29. // flushWriter provides wrapper for responseWriter with HTTP streaming capabilities
  30. type flushWriter struct {
  31. flusher http.Flusher
  32. writer io.Writer
  33. }
  34. // Write is a FlushWriter implementation of the io.Writer that sends any buffered
  35. // data to the client.
  36. func (fw *flushWriter) Write(p []byte) (n int, err error) {
  37. n, err = fw.writer.Write(p)
  38. if err != nil {
  39. return
  40. }
  41. if fw.flusher != nil {
  42. fw.flusher.Flush()
  43. }
  44. return
  45. }