gin icon indicating copy to clipboard operation
gin copied to clipboard

c.Data and c.DataFromReader overwrite the set header

Open alimoli opened this issue 1 year ago • 1 comments

Description

c.Data and c.DataFromReader overwrite the set header.

How to reproduce

package main

import (
	"github.com/gin-gonic/gin"
)

func main() {
	g := gin.Default()
	g.GET("/hello/:name", func(c *gin.Context) {
	     
             var compressedBuffer bytes.Buffer
             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

alimoli avatar Apr 30 '24 12:04 alimoli

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

RedCrazyGhost avatar May 01 '24 15:05 RedCrazyGhost

@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

alimoli avatar May 22 '24 11:05 alimoli