如何避免发送Content-Length标头

时间:2014-06-23 10:05:21

标签: go

对于流式http端点,是否有办法避免发送长度?

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

这就是我的回忆。

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

服务器也会打印警告。

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

1 个答案:

答案 0 :(得分:6)

您不应手动设置Transfer-Encoding。 Go会为你做这件事,以及Content-Length

curl,Go http客户端或任何标准http客户端将自动正确读取分块或非分块的http响应。

分块服务器的小例子: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!\n")
                w.(http.Flusher).Flush()
        }
}

func main() {
        http.HandleFunc("/", HelloServer)
        err := http.ListenAndServe(":8080", nil)
        if err != nil {
                log.Fatal("ListenAndServe: ", err)
        }
}

在图像/ jpeg的情况下,您可以将分块的决定委托给Go,或者手动从图像中发送N个字节,然后刷新。