Home > Blockchain >  what is the differences between r.Static() and context.File() to get the picture in gin?
what is the differences between r.Static() and context.File() to get the picture in gin?

Time:10-26

I'm developing a Go program based on Gin web framework.

I want to serve pictures from the local file system.

enter image description here

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?

CodePudding user response:

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.

  • Related