blob: 748bd010856bc634e0f90ffb35d9752cede6e89c [file] [log] [blame]
Matthias Andreas Benkard832a54e2019-01-29 09:27:38 +01001/*
2Copyright 2014 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package flushwriter
18
19import (
20 "io"
21 "net/http"
22)
23
24// Wrap wraps an io.Writer into a writer that flushes after every write if
25// the writer implements the Flusher interface.
26func Wrap(w io.Writer) io.Writer {
27 fw := &flushWriter{
28 writer: w,
29 }
30 if flusher, ok := w.(http.Flusher); ok {
31 fw.flusher = flusher
32 }
33 return fw
34}
35
36// flushWriter provides wrapper for responseWriter with HTTP streaming capabilities
37type flushWriter struct {
38 flusher http.Flusher
39 writer io.Writer
40}
41
42// Write is a FlushWriter implementation of the io.Writer that sends any buffered
43// data to the client.
44func (fw *flushWriter) Write(p []byte) (n int, err error) {
45 n, err = fw.writer.Write(p)
46 if err != nil {
47 return
48 }
49 if fw.flusher != nil {
50 fw.flusher.Flush()
51 }
52 return
53}