Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
alimoli opened this issue Apr 30, 2024 · 2 comments
Closed

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

alimoli opened this issue Apr 30, 2024 · 2 comments

Comments

@alimoli
Copy link

alimoli commented Apr 30, 2024

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
@RedCrazyGhost
Copy link
Contributor

RedCrazyGhost commented May 1, 2024

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

@alimoli
Copy link
Author

alimoli commented May 22, 2024

@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 alimoli closed this as completed May 22, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants