writer.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright 2019 Yunion
  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. Copyright 2014 The Kubernetes Authors.
  16. Licensed under the Apache License, Version 2.0 (the "License");
  17. you may not use this file except in compliance with the License.
  18. You may obtain a copy of the License at
  19. http://www.apache.org/licenses/LICENSE-2.0
  20. Unless required by applicable law or agreed to in writing, software
  21. distributed under the License is distributed on an "AS IS" BASIS,
  22. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  23. See the License for the specific language governing permissions and
  24. limitations under the License.
  25. */
  26. package flushwriter
  27. import (
  28. "io"
  29. "net/http"
  30. )
  31. // Wrap wraps an io.Writer into a writer that flushes after every write if
  32. // the writer implements the Flusher interface.
  33. func Wrap(w io.Writer) io.Writer {
  34. fw := &flushWriter{
  35. writer: w,
  36. }
  37. if flusher, ok := w.(http.Flusher); ok {
  38. fw.flusher = flusher
  39. }
  40. return fw
  41. }
  42. // flushWriter provides wrapper for responseWriter with HTTP streaming capabilities
  43. type flushWriter struct {
  44. flusher http.Flusher
  45. writer io.Writer
  46. }
  47. func (fw *flushWriter) Write(p []byte) (n int, err error) {
  48. n, err = fw.writer.Write(p)
  49. if err != nil {
  50. return
  51. }
  52. if fw.flusher != nil {
  53. fw.flusher.Flush()
  54. }
  55. return
  56. }