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

Dan*_*any 5 encoding http go

我正在使用 net/http 包在 GO 中编写一个小型实验性 http 服务器,我需要所有回复都具有“身份”传输编码。然而,GO 中的 http 服务器总是使用“分块”传输返回响应。有什么方法可以禁用 GO 中 HTTP 服务器上的分块编码?

las*_*owh 2

我不清楚用“传输编码:身份”进行响应在规范下是否有效(我认为也许你应该忽略它),但是......

检查此处的代码,我在 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 {
Run Code Online (Sandbox Code Playgroud)

我相信上面第一行中的“hasCL”是指具有可用的内容长度。如果可用,它将完全删除“Transfer-Encoding”标头,否则,如果版本为 1.1 或更高版本,它将“Transfer-Encoding”设置为分块。因为这是在将其写入套接字之前完成的,所以我认为当前没有任何方法可以更改它。