英文:
Disable chunked encoding for HTTP server responses
问题
我正在使用net/http包在GO中编写一个小型实验性的HTTP服务器,并且我需要所有的回复都使用'identity'传输编码。然而,GO中的HTTP服务器总是使用'chunked'传输返回响应。
有没有办法在GO的HTTP服务器上禁用分块编码?
英文:
I'm writing a small experimental http server in GO using the net/http package, and I need all my replies to have 'identity' transfer encoding. However the http server in GO always returns responses using the 'chunked' transfer.
Is there any way to disable chunked encoding on HTTP server in GO?
答案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或更高版本:使用分块传输编码
372 //以避免在EOF时关闭连接。
373 // TODO:这将覆盖任何自定义或堆叠的Transfer-Encoding。
374 //一旦我们有一个有效的用例,根据需要处理它。
375 w.chunking = true
376 w.header.Set("Transfer-Encoding", "chunked")
377 } else {
我相信上面第一行中的“hasCL”是指是否有可用的内容长度。如果有可用的内容长度,它将完全删除“Transfer-Encoding”头部,否则,如果版本是1.1或更高,则将“Transfer-Encoding”设置为chunked。因为这是在写入套接字之前执行的,所以我认为目前没有任何方法可以更改它。
英文:
It's not clear to me whether responding with "Transfer-Encoding: identity" is valid under the spec (I think maybe you should just leave it out), but...
Inspecting the code here, I see this inside the WriteHeader(code int) function (it's a little bit strange, but this function actually flushes all the headers to the socket):
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 {
I believe "hasCL" in the first line above refers to having a content length available. If it is available, it removes the "Transfer-Encoding" header altogether, otherwise, if the version is 1.1 or greater, it sets the "Transfer-Encoding" to chunked. Because this is done right before writing it to the socket, I don't think there's currently going to be any way for you to change it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论