我有一个go API,到目前为止一直返回JSON。我使用chi路由器并在我的主要功能中使用这样的中间件来设置它:
func router() http.Handler {
r := chi.NewRouter()
r.Use(render.SetContentType(render.ContentTypeJSON))
....现在,我想在某些函数中返回各种类型的文件。如果在路由器功能中设置如下内容类型
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
}这会覆盖此函数的内容类型的呈现设置吗?
发布于 2022-09-07 14:21:16
是的,您可以通过简单地设置Content-Type:头来设置内容类型,但是您需要这样做,然后才能像这样调用w.WriteHeader(http.StatusOK):
w.Header().Set("Content-Type", "application/octet-stream")
w.WriteHeader(http.StatusOK)
w.Write(fileBytes)否则,您将在将标题写入响应后进行更改,并且不会产生任何影响。
https://stackoverflow.com/questions/73631831
复制相似问题