Debian Codegraph @

pkg/util/flushwriter/writer.go

raw
1 /*
2 Copyright 2014 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package flushwriter
18
19 import (
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.
26 func 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
37 type 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.
44 func (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 }