Description
c.Data
and c.DataFromReader
overwrite the set header.
How to reproduce
package main
import (
"bytes"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
g := gin.Default()
g.GET("/hello", func(c *gin.Context) {
var compressedBuffer bytes.Buffer
// Solution 1 (not working)
contentLength := int64(compressedBuffer.Len())
c.DataFromReader(
http.StatusOK, contentLength, "text/csv", &compressedBuffer, map[string]string{
"Content-Encoding": "gzip",
"X-Content-Encoding": "hawaii",
},
)
// Solution 2 (not working)
// c.Header("Content-Encoding", "gzip")
// c.Data(http.StatusOK, "text/csv", compressedBuffer.Bytes())
})
g.Run(":9000")
}
Expectations
I expect to see the set headers in the response, but only Content-Type
is set. I want to get also Content-Encoding
.
Actual result
Only content type is set.
Environment
- go version: 1.22.1 darwin/arm64
- gin version (or commit ref): 1.9.1
- operating system: Mac OS Sonoma 14.2.1
Comment From: RedCrazyGhost
I tested the code you provided and there is no problem. The return value of apifox is normal. Please check the response header! The code logic of gin code is normal.
Environment
- go version: go1.21.3 darwin/amd64
- gin version: github.com/gin-gonic/gin v1.9.1
- operating system: Mac OS 14.4.1
Comment From: alimoli
@RedCrazyGhost I don't know exactly all the dynamics here, but I found the problem.
My testing client has no Accept-Encoding
header in the request.
With that header in the request, the response includes the Content-Encoding
.
Most of HTTP clients have this Accept-Encoding
set to gzip, deflate
by default.
This is why I haven't this problem in other situations.
Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding#compressing_with_gzip