From e3bcb06c3eda1c2f43674fb367a536a80f43db9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=96=E7=95=8C?= Date: Thu, 26 Mar 2026 16:49:28 +0800 Subject: [PATCH] platform: Add HTTPResponse.WriteToWithProgress --- experimental/libbox/http.go | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/experimental/libbox/http.go b/experimental/libbox/http.go index 9f4b2915c..69a23d264 100644 --- a/experimental/libbox/http.go +++ b/experimental/libbox/http.go @@ -52,6 +52,11 @@ type HTTPRequest interface { type HTTPResponse interface { GetContent() (*StringBox, error) WriteTo(path string) error + WriteToWithProgress(path string, handler HTTPResponseWriteToProgressHandler) error +} + +type HTTPResponseWriteToProgressHandler interface { + Update(progress int64, total int64) } var ( @@ -239,3 +244,31 @@ func (h *httpResponse) WriteTo(path string) error { defer file.Close() return common.Error(bufio.Copy(file, h.Body)) } + +func (h *httpResponse) WriteToWithProgress(path string, handler HTTPResponseWriteToProgressHandler) error { + defer h.Body.Close() + file, err := os.Create(path) + if err != nil { + return err + } + defer file.Close() + return common.Error(bufio.Copy(&progressWriter{ + writer: file, + handler: handler, + total: h.ContentLength, + }, h.Body)) +} + +type progressWriter struct { + writer io.Writer + handler HTTPResponseWriteToProgressHandler + total int64 + written int64 +} + +func (w *progressWriter) Write(p []byte) (int, error) { + n, err := w.writer.Write(p) + w.written += int64(n) + w.handler.Update(w.written, w.total) + return n, err +}