Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement flushing copy on proxy response #416

Merged
merged 1 commit into from
Oct 26, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion http/proxy_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -324,12 +324,34 @@ func (s *ProxyServer) proxyToTarget(w http.ResponseWriter, r *http.Request, pass

// Set response code and copy the body.
w.WriteHeader(resp.StatusCode)
if _, err := io.Copy(w, resp.Body); err != nil {
if err := copyAndFlush(w, resp.Body); err != nil {
log.Printf("http: proxy response error: %s", err)
return
}
}

// copyAndFlush implements a basic io.Copy() but calls dst.Flush() after every write.
// dst must implement http.Flusher or else it will panic.
func copyAndFlush(dst io.Writer, src io.Reader) error {
buf := make([]byte, 32*1024)

for {
n, err := src.Read(buf)
if n > 0 {
if _, e := dst.Write(buf[:n]); e != nil {
return err
}
dst.(http.Flusher).Flush()
}

if err == io.EOF {
return nil
} else if err != nil {
return err
}
}
}

func (s *ProxyServer) isWriteRequest(r *http.Request) bool {
return r.Method != http.MethodGet && r.Method != http.MethodHead
}
Expand Down
Loading