I have a simple HTTP server written in golang using echo v4. When the response size is bigger than a certain size (threshold is 2.12K as I have tested), server sets the Transfer-Encoding header to chunked and sends the response in multiple chunks, but for smaller responses, the server does not set the Transfer-Encoding header and sends the response body plain.
I want to control this behavior, so that I can define the threshold where the echo HTTP server starts to chunk the response body. My google searches show that I can obtain this by manipulating the ResponseWriter, but I could not figure out how to do that in my code.
This is my code:
func main() {
e := echo.New()
e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.GET("/hi", func(c echo.Context) error {
data := make(map[int]string)
for i := 0; i < repeatCount; i++ {
data[i] = strings.Repeat("z", i)
}
return c.JSON(http.StatusOK, data)
})
e.Logger.Fatal(e.Start(":3000"))
}
Can anyone please help me here?
The net/http server uses the identify transfer encoding when Content-Length header is set. If the length of the response body is known, set the content length header before writing to the response:
The application can buffer the response to compute the content length:
The net/http server uses the identity transfer encoding when the Transfer-Encoding header is set to identity. The server terminates the response body by closing the connection. The client reads the response body to EOF. Set the header before writing to the response.
The net/http server buffers 2048 bytes of the response body. The application cannot change the size of this buffer. If the entire response body fits within this buffer, the server sets the Content-Length header and uses the identity transfer encoding.
Otherwise, the server uses chunked encoding.
Use an application controlled buffer to change the threshold at which chunking occurs: