Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

multipart upload with io.Pipe

View client.go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
package main
 
import (
"io"
"log"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"runtime"
 
"github.com/cheggaaa/pb"
)
 
func main() {
if len(os.Args) != 2 {
log.Println("Usage: pipeUp <filename>\n")
os.Exit(1)
}
 
input, err := os.Open(os.Args[1])
check(err)
defer input.Close()
 
stat, err := input.Stat()
check(err)
 
pipeOut, pipeIn := io.Pipe()
fsize := stat.Size()
bar := pb.New(int(fsize)).SetUnits(pb.U_BYTES)
bar.ShowSpeed = true
 
writer := multipart.NewWriter(pipeIn)
 
// do the request concurrently
var resp *http.Response
done := make(chan error)
go func() {
 
// prepare request
req, err := http.NewRequest("POST", "http://localhost:9000/upload", pipeOut)
if err != nil {
done <- err
return
}
req.ContentLength = fsize // filesize
req.ContentLength += 227 // multipart header exclouding filename
req.ContentLength += int64(len(os.Args[1]))
req.ContentLength += 19
 
req.Header.Set("Content-Type", writer.FormDataContentType())
log.Println("Created Request")
bar.Start()
 
resp, err = http.DefaultClient.Do(req)
if err != nil {
done <- err
return
}
 
done <- nil
}()
 
part, err := writer.CreateFormFile("file", filepath.Base(os.Args[1]))
check(err)
 
out := io.MultiWriter(part, bar)
_, err = io.Copy(out, input)
check(err)
 
check(writer.Close())
check(pipeIn.Close()) // need to close the pipe to
 
check(<-done)
 
bar.FinishPrint("Upload done!")
 
}
 
func check(err error) {
_, file, line, _ := runtime.Caller(1)
if err != nil {
log.Fatalf("Fatal from <%s:%d>\nError:%s", file, line, err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.