Skip to content

Instantly share code, notes, and snippets.

@AnjanaMadu
Created September 18, 2022 12:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AnjanaMadu/52c5d654341ac70a0f52c477bdac5c6b to your computer and use it in GitHub Desktop.
Save AnjanaMadu/52c5d654341ac70a0f52c477bdac5c6b to your computer and use it in GitHub Desktop.
Golang http multipart post upload/sent progress tracker.
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