I have a jpeg image.Image
and I want to decode
to a request body. Simplified below, it doesn't seem to finish the request ever. The program hangs.
r, w := io.Pipe()
jpeg.Encode(w, img, &jpeg.Options{ 80 })
req, e := http.NewRequest("PUT", myUrl, r)
if e != nil {
return nil, e
}
http.DefaultClient.Do(req)
How can I write an image to the request body?
Just use a buffer
var w bytes.Buffer
jpeg.Encode(&w, img, &jpeg.Options{80})
req, e := http.NewRequest("PUT", myUrl, &w)
if e != nil {
log.Fatal(e)
}
http.DefaultClient.Do(req)
jpeg.Encode
can't procede, because it's blocked writing to the pipe (pipes don't buffer).
You either need to buffer the encoded image, or run the Encode and http request concurrently.
// make sure to buffer this channel, so the goroutine can exit if we return early
errChan := make(chan error, 1)
r, w := io.Pipe()
go func() {
errChan <- jpeg.Encode(w, img, &jpeg.Options{80})
}()
req, err := http.NewRequest("PUT", myUrl, r)
if err != nil {
return nil, err
}
err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
// check for an encoding error
err := <-errChan
if err != nil {
return nil, err
}