英文:
echo server distorting image response body
问题
尝试编写一个简单的图像回显服务器,但是它会扭曲文件。出了什么问题?
package main
import (
"fmt"
"io"
"net/http"
)
type FlushWriter struct {
w io.Writer
}
func (fw *FlushWriter) Write(bytes []byte) (int, error) {
count, e := fw.w.Write(bytes)
fw.w.(http.Flusher).Flush()
return count, e
}
func main() {
http.HandleFunc("/", index)
fmt.Println("listening on 8000")
http.ListenAndServe(":8000", nil)
}
func index(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "image/jpeg")
fw := &FlushWriter{w: w}
io.Copy(fw, r.Body)
}
并进行测试。
$ curl --data-binary @image.jpg -o test.jpg localhost:8000
请注意,这段代码是一个简单的图像回显服务器,它将接收到的图像数据直接写入响应中。如果图像文件被扭曲,可能是由于以下原因之一:
- 图像文件本身已经损坏或扭曲。
- 服务器端代码存在问题,导致图像数据在传输过程中被修改。
你可以尝试以下步骤来排除问题:
- 确保图像文件本身没有损坏,尝试打开图像文件并检查是否能够正确显示。
- 检查服务器端代码中的错误,确保没有对图像数据进行修改或处理的代码。
- 尝试使用其他图像文件进行测试,看是否仍然存在扭曲问题。
如果问题仍然存在,请提供更多的详细信息,以便我能够更好地帮助你解决问题。
英文:
Trying to write a simple echo server for images, but it distorts the file. What's going wrong?
package main
import (
"fmt"
"io"
"net/http"
)
type FlushWriter struct {
w io.Writer
}
func (fw *FlushWriter) Write(bytes []byte) (int, error) {
count, e := fw.w.Write(bytes)
fw.w.(http.Flusher).Flush()
return count, e
}
func main() {
http.HandleFunc("/", index)
fmt.Println("listening on 8000")
http.ListenAndServe(":8000", nil)
}
func index(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "image/jpeg")
fw := &FlushWriter{ w: w }
io.Copy(fw, r.Body)
}
And to test it.
$ curl --data-binary @image.jpg -o test.jpg localhost:8000
答案1
得分: 2
你的代码中忽略了错误,并且缺少了ErrBodyReadAfterClose
。
一旦开始向http.ResponseWriter
写入数据,就无法从http.Request.Body
中读取数据。
你需要在服务器上缓冲图像,然后再将其写回。
除了Go语言不允许这样做之外,即使你创建了一个可以工作的处理程序,大多数客户端也会导致在涉及所有缓冲区的图像总大小大于缓冲区之和时发生死锁。这需要一个能够同时发送和接收数据的客户端,而这样的客户端非常少,甚至可以说几乎没有。
英文:
You're ignoring errors in your code, and missing a ErrBodyReadAfterClose
.
You can't read from the http.Request.Body
once you start writing to the http.ResponseWriter
http://golang.org/pkg/net/http/#pkg-variables
> ErrBodyReadAfterClose is returned when reading a Request or Response
> Body after the body has been closed. This typically happens when the
> body is read after an HTTP Handler calls WriteHeader or Write on its
> ResponseWriter
You'll need to buffer the image on the server before writing it back.
Aside from the fact that Go won't let you do this, even if you were to make a handler that worked, most clients would cause this to deadlock with images larger than the sum of all the buffers involved. This requires a client that can simultaniously send and receive, which very few, if any would do.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论