我正在创建一个测试Go HTTP服务器,我正在发送Transfer-Encoding的响应头:chunked所以我可以在检索它时不断发送新数据.此服务器应每秒向此服务器写一个块.客户应该能够按需接收它们.
不幸的是,客户端(在这种情况下卷曲)在持续时间结束时接收所有块,5秒,而不是每秒接收一个块.此外,Go似乎为我发送了Content-Length.我想在最后发送Content-Length,我希望标题的值为0.
这是服务器代码:
package main
import (
"fmt"
"io"
"log"
"net/http"
"time"
)
func main() {
http.HandleFunc("/test", HandlePost);
log.Fatal(http.ListenAndServe(":8080", nil))
}
func HandlePost(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Connection", "Keep-Alive")
w.Header().Set("Transfer-Encoding", "chunked")
w.Header().Set("X-Content-Type-Options", "nosniff")
ticker := time.NewTicker(time.Second)
go func() {
for t := range ticker.C {
io.WriteString(w, "Chunk")
fmt.Println("Tick at", t)
}
}()
time.Sleep(time.Second * 5)
ticker.Stop()
fmt.Println("Finished: should return Content-Length: 0 here")
w.Header().Set("Content-Length", "0")
}
Run Code Online (Sandbox Code Playgroud) 我有一个测试节点服务器,每隔两秒发送一次带有以下标头的分块响应:
response.setHeader('Content-Type', 'text/plain')
response.setHeader('Transfer-Encoding', 'chunked')
Run Code Online (Sandbox Code Playgroud)
每隔两秒,我就会写下回复:
response.write('Hello World');
Run Code Online (Sandbox Code Playgroud)
当我在端点上执行卷曲时,我每两秒就会收到一个块:
Hello World
(wait two seconds)
Hello World
(wait two seconds)
Hello World
Run Code Online (Sandbox Code Playgroud)
它的工作原理就像在卷曲中应该的那样。
对于客户端的 Javascript,我设置了一个新的函数XMLHttpRequest并分配了一个函数来打印该responseText事件的函数onprogress。这是不同浏览器的实现似乎有所不同的地方。
在 Firefox 和 Safari 中,我得到与卷曲时类似的行为。每个“Hello World”都会触发一个 onprogress 事件。
在 Chrome 中,仅当收到所有块并且我response.end()在服务器端执行 a 时,才会触发 onprogress 事件。当我尝试打印出 时responseText,只打印出一个空字符串。
客户端代码如下所示:
var xhr = new XMLHttpRequest()
xhr.onprogress = function() {
// Firefox, Safari prints out an accumulation of the chunks
// Chrome prints out an empty string
console.log(xhr.responseText);
}
Run Code Online (Sandbox Code Playgroud)