Created
September 18, 2022 12:36
-
-
Save AnjanaMadu/52c5d654341ac70a0f52c477bdac5c6b to your computer and use it in GitHub Desktop.
Golang http multipart post upload/sent progress tracker.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"fmt" | |
"io" | |
"io/ioutil" | |
"mime/multipart" | |
"net/http" | |
"os" | |
) | |
type Tracker struct { | |
io.Reader | |
sent int | |
} | |
func (r *Tracker) Read(p []byte) (n int, err error) { | |
n, err = r.Reader.Read(p) | |
r.sent += n | |
fmt.Printf("Read %d bytes\r", r.sent) | |
return | |
} | |
// Close the reader when it implements io.Closer | |
func (r *Tracker) Close() (err error) { | |
if closer, ok := r.Reader.(io.Closer); ok { | |
return closer.Close() | |
} | |
return | |
} | |
func main() { | |
body := &bytes.Buffer{} | |
bodyWriter := multipart.NewWriter(body) | |
fw, _ := bodyWriter.CreateFormFile("file", "file") | |
fh, _ := os.Open("file") | |
io.Copy(fw, fh) | |
bodyWriter.Close() | |
reader := &Tracker{body, 0} | |
resp, _ := http.Post("http://httpbin.org/post", bodyWriter.FormDataContentType(), reader) | |
defer resp.Body.Close() | |
response, _ := ioutil.ReadAll(resp.Body) | |
print(string(response)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment