繁体   English   中英

处理程序是否假设在 http 响应 header 中填充内容类型?

[英]Is the handler suppose to populate content-type in http response header?

下面的处理程序处理GET请求,而不填充 http Response header:

// 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 header:

// 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 header?

始终首先阅读文档!

这里清楚地涵盖了这个问题的答案(显然添加了重点):

// 如果 WriteHeader 还没有被调用,Write 调用
// 写入数据前的 WriteHeader(http.StatusOK)。 如果 Header
// 不包含 Content-Type 行,Write 添加一个 Content-Type 集
// 将初始 512 字节的写入数据传递给的结果
// 检测内容类型。 此外,如果所有写入的总大小
// 数据小于几 KB 并且没有 Flush 调用,
// 自动添加内容长度 header。

要明确回答您的次要问题:

我们什么时候需要填充content-type header?

任何时候您不希望它被自动检测到。 自动检测是不精确的,因此您通常不想依赖它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM