英文:
how to write image to request body
问题
我有一个image.Image
的JPEG图像,我想将其解码为请求体。下面是简化的代码,但似乎永远无法完成请求。程序卡住了。
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)
我该如何将图像写入请求体?
英文:
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?
答案1
得分: 2
只需使用缓冲区
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)
英文:
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)
答案2
得分: 1
jpeg.Encode
无法进行处理,因为它被阻止写入管道(管道不具有缓冲区)。
你可以选择对编码后的图像进行缓冲,或者同时运行Encode和http请求。
// 确保对该通道进行缓冲,这样goroutine在我们提前返回时可以退出
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
}
// 检查是否有编码错误
err = <-errChan
if err != nil {
return nil, err
}
英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论