【问题标题】:Is the handler suppose to populate content-type in http response header?处理程序是否假设在 http 响应标头中填充内容类型?
【发布时间】: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 标头?

【问题讨论】:

    标签: http go


    【解决方案1】:

    始终先阅读文档!

    here 的答案很明显(重点明显添加):

    // 如果 WriteHeader 还没有被调用,Write 调用
    // 写入数据前的 WriteHeader(http.StatusOK)。 如果标题
    // 不包含 Content-Type 行,Write 添加一个 Content-Type 集
    // 将最初的 512 字节写入数据传递给
    的结果 // DetectContentType.
    另外,如果所有写入的总大小
    // 数据小于几 KB,并且没有 Flush 调用,
    // 自动添加 Content-Length 标头。

    明确回答您的第二个问题:

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

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

    【讨论】:

    • “自动检测不精确”这一点很重要。其他点可能是响应是按块创建的,因此自动检测甚至可能不起作用,因为还没有足够的数据可用。如果类型明确,也许有人可能想简单地跳过使用 DetectContentType 的开销。
    猜你喜欢
    • 2011-09-30
    • 2011-08-14
    • 2021-05-23
    • 2014-06-03
    • 2015-07-19
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多