禁用HTTP服务器响应的分块编码

5

我正在使用net/http包在GO语言中编写一个小型的实验性http服务器,并且需要所有的回复都采用'identity'传输编码。然而,GO语言中的http服务器总是使用'chunked'传输返回响应。 有没有办法在GO语言的HTTP服务器上禁用chunked编码?


1
你需要添加一个 Content-Length 头部 ;) - thwd
1
一个 golang-nuts 的线程涉及到了这个话题:https://groups.google.com/d/topic/golang-nuts/3sYwQlUOv-o/discussion - zzzz
1
谢谢@Tom!Content-Length头字符串中有一个错别字。这个修复了一切 :) - Dany
1个回答

2

我不确定按规范回复"Transfer-Encoding: identity"是否有效(也许你应该省略它),但是...

检查这里的代码,我发现在WriteHeader(code int)函数中有以下内容(有点奇怪,但是这个函数实际上将所有标头刷新到套接字):

367     } else if hasCL {
368         w.contentLength = contentLength
369         w.header.Del("Transfer-Encoding")
370     } else if w.req.ProtoAtLeast(1, 1) {
371         // HTTP/1.1 or greater: use chunked transfer encoding
372         // to avoid closing the connection at EOF.
373         // TODO: this blows away any custom or stacked Transfer-Encoding they
374         // might have set.  Deal with that as need arises once we have a valid
375         // use case.
376         w.chunking = true
377         w.header.Set("Transfer-Encoding", "chunked")
378     } else {

我认为上述第一行中的“hasCL”是指已有可用的内容长度。如果有,则完全删除“Transfer-Encoding”头,否则,如果版本号大于等于1.1,则将“Transfer-Encoding”设置为分块传输。由于这是在写入套接字之前进行的,因此我认为目前没有任何方法可以更改它。


添加Content-Length就可以解决问题了。(我在那个头部有一个打字错误)。谢谢! - Dany
1
但是如果您不知道内容长度呢? - Timmmm
@Timmmm,那么没有人应该与您的客户端/代理通信,因为它设计得很差,遵循了HTTP1.1中存在问题的部分,而HTTP2已经移除了这些问题。 - MrMesees

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接