dongzhang6544 2014-06-23 10:05
浏览 318
已采纳

如何避免发送Content-Length标头

For a streaming http endpoint is there a way to refrain from sending the length?

  w.Header().Set("Content-Type", "image/jpeg")
  w.Header().Set("Transfer-Encoding", "chunked")
  w.Header().Del("Content-Length")

This is what I get back.

HTTP/1.1 200 OK
Content-Length: 0
Content-Type: image/jpeg
Date: Mon, 23 Jun 2014 10:00:59 GMT
Transfer-Encoding: chunked
Transfer-Encoding: chunked

The server prints a warning as well.

2014/06/23 06:04:03 http: WriteHeader called with both Transfer-Encoding of "chunked" and a Content-Length of 0
  • 写回答

1条回答 默认 最新

  • douchao0358 2014-06-23 10:56
    关注

    You should not manually set the Transfer-Encoding. Go is going to do that for you, as well as the Content-Length.

    curl, the Go http client or any standard http client will automatically read correctly chunked or non-chunked http response.

    Small exmaple of chunked server: http://play.golang.org/p/miEV7URi8P

    package main
    
    import (
            "io"
            "log"
            "net/http"
    )
    
    // hello world, the web server
    func HelloServer(w http.ResponseWriter, req *http.Request) {
            w.WriteHeader(200)
            for i := 0; i < 5; i++ {
                    io.WriteString(w, "hello, world!
    ")
                    w.(http.Flusher).Flush()
            }
    }
    
    func main() {
            http.HandleFunc("/", HelloServer)
            err := http.ListenAndServe(":8080", nil)
            if err != nil {
                    log.Fatal("ListenAndServe: ", err)
            }
    }
    

    In a case of an image/jpeg, you can either delegate the chunked decision to Go or manually send N bytes from the image then flush.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?