go-chi路由器覆盖中间件以设置内容类型

huangapple go评论90阅读模式
英文:

go-chi router override middleware to set content type

问题

你好!根据你的描述,你想知道在使用chi路由器设置中间件时,如果在某些函数中设置了Content-Type,是否会覆盖路由器设置的Content-Type。

根据我的理解,路由器设置的Content-Type是应用于整个路由器的,而在单个函数中设置的Content-Type只会影响该函数的响应。所以在你的例子中,如果你在handleRequest函数中设置了Content-Type为"application/octet-stream",它只会影响该函数的响应,不会覆盖路由器设置的Content-Type。

换句话说,handleRequest函数中的设置不会影响其他函数的响应,它们仍然会使用路由器设置的Content-Type。

希望这个解释对你有帮助!如果还有其他问题,请随时提问。

英文:

I have a go API which so far has always returned JSON. I use chi router and set it up using middleware like this in my main function:

func router() http.Handler {

r := chi.NewRouter()
r.Use(render.SetContentType(render.ContentTypeJSON))
....

Now I want to return a file of various types in some functions. If I set the content type like this in my router function

func handleRequest(w http.ResponseWriter, r *http.Request) {
	fileBytes, err := ioutil.ReadFile("test.png")
	if err != nil {
		panic(err)
	}
	w.WriteHeader(http.StatusOK)
	w.Header().Set("Content-Type", "application/octet-stream")
	w.Write(fileBytes)
	return
}

Will that override the render setting for the content-type for this function?

答案1

得分: 3

是的,你可以通过简单地设置Content-Type头来设置内容类型,但是你需要在实际调用w.WriteHeader(http.StatusOK)之前这样做,就像这样:

w.Header().Set("Content-Type", "application/octet-stream")
w.WriteHeader(http.StatusOK)
w.Write(fileBytes)

否则,你是在响应头已经写入之后进行更改,这将没有任何效果。

英文:

Yes, you can set content type by simply setting Content-Type: header, but you need to do that before you actually call w.WriteHeader(http.StatusOK) like this:

w.Header().Set("Content-Type", "application/octet-stream")
w.WriteHeader(http.StatusOK)
w.Write(fileBytes)

otherwise you are making change after headers were written to the response and it will have no effect.

huangapple
  • 本文由 发表于 2022年9月7日 15:48:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/73631831.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定