英文:
what is the differences between r.Static() and context.File() to get the picture in gin?
问题
我正在基于Gin Web框架开发一个Go程序。
我想从本地文件系统中提供图片。
func main() {
r := gin.Default()
r.Static("/page2", "resources/pictures")
r.GET("/test", func(context *gin.Context) {
name := context.Query("name")
context.JSON(http.StatusOK, gin.H{
"name": name,
})
})
r.GET("/page", func(context *gin.Context) {
name := context.Query("picname")
context.File("resources/pictures/" + name + ".jpg")
context.JSON(http.StatusOK, "That is "+name)
})
r.Run(":9090")
}
我发现当我使用/page2
来获取图片(URL为http://localhost:9090/page2/xiamei.jpg
)时,一切正常。
但是当我使用/page
来获取图片(URL为http://localhost:9090/page/xiamei.jpg
)时,出现了错误。
http: wrote more than the declared Content-Length
这是什么内部原因,这两种访问方法之间的差异的根本原因是什么?
英文:
I'm developing a Go program based on Gin web framework.
I want to serve pictures from the local file system.
func main() {
r := gin.Default()
r.Static("/page2", "resources/pictures")
r.GET("/test", func(context *gin.Context) {
name := context.Query("name")
context.JSON(http.StatusOK, gin.H{
"name": name,
})
})
r.GET("/page", func(context *gin.Context) {
name := context.Query("picname")
context.File("resources/pictures/" + name + ".jpg")
context.JSON(http.StatusOK, "That is "+name)
})
r.Run(":9090")
}
I find it strange that when I use /page2
to get the pictures (url http://localhost:9090/page2/xiamei.jpg
), it works fine.
But when I use /page
to get the pictures (url http://localhost:9090/page/xiamei.jpg
) an error happens.
> http: wrote more than the declared Content-Length
What is the internal reason, and what is the root cause of the difference between these two access methods?
答案1
得分: 0
在/page
处理程序中,你同时调用了Context.File
和Context.JSON
。
第一次调用Context.File
已经将文件写入响应并设置了Content-Length
头。
通过再次使用更多的有效负载调用Context.JSON
,你增加了实际内容的长度,但没有更新Content-Length
头;这导致了你看到的错误。
r.Static
没有这个问题,因为它只提供一个文件,并且不会添加超过应有的有效负载。
在Gin处理程序中,你应该只调用一个渲染器函数。如果你正在提供一个文件,你可以完全删除最后一个c.JSON
。
英文:
In the /page
handler, you call both Context.File
, and Context.JSON
.
The first call to Context.File
already writes the file to the response and sets Content-Length
header.
By calling Context.JSON
again with more payload, you are increasing the actual length of the content without updating the Content-Length
header; this results in the error you see.
r.Static
doesn't have this issue because it serves one file and doesn't add more payload than it should.
In a Gin handler you should call only one renderer function. If you are serving a file, you can remove the last c.JSON
altogether.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论