【发布时间】:2020-06-21 06:46:30
【问题描述】:
下面的处理程序处理 GET 请求,而不填充 http Response 标头:
// ListAll handles GET requests and returns all current products
func (p *ProductHandler) ListAll(rw http.ResponseWriter, r *http.Request) {
p.l.Println("[DEBUG] get all records")
prods := data.GetProducts()
err := data.ToJSON(prods, rw)
if err != nil {
// we should never be here but log the error just incase
p.l.Println("[ERROR] serializing product", err)
}
}
以下处理程序处理GET 请求,填充http Response 标头:
// ListAll handles GET requests and returns all current products
func (p *ProductHandler) ListAll(rw http.ResponseWriter, r *http.Request) {
p.l.Println("[DEBUG] get all records")
rw.Header().Add("Content-Type", "application/json")
prods := data.GetProducts()
err := data.ToJSON(prods, rw)
if err != nil {
// we should never be here but log the error just incase
p.l.Println("[ERROR] serializing product", err)
}
}
这两种情况都适用于简单的 curl 请求。
对于任何 http 客户端,
我们什么时候需要在向客户端发送响应之前填充content-type 标头?
【问题讨论】: