我有一个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
}
这会覆盖此函数的内容类型的渲染设置吗?
是的,您可以通过简单地设置Content-Type:
标头来设置内容类型,但在实际调用w.WriteHeader(http.StatusOK)
之前需要这样做:
w.Header().Set("Content-Type", "application/octet-stream")
w.WriteHeader(http.StatusOK)
w.Write(fileBytes)
否则,在将头写入响应后进行更改,将不会产生任何效果。