Go:http Transfer-Encoding chunked 实时读写
服务端:
package main
import (
"fmt"
"net/http"
"time"
)
func main() {
http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
flusher, ok := writer.(http.Flusher)
if !ok {
panic("expected http.ResponseWriter to be an http.Flusher")
}
for i := 0; i < 16; i++ {
fmt.Fprintf(writer, "chunk [%02d]: %v\n", i, time.Now())
flusher.Flush()
time.Sleep(time.Second)
}
})
http.ListenAndServe(":9080", nil)
}
参考:
https://stackoverflow.com/questions/26769626/send-a-chunked-http-response-from-a-go-server
客户端:
package main
import (
"fmt"
"io"
"net/http"
"strings"
)
func main() {
resp, err := http.Post("http://127.0.0.1:9080/", "application/json", strings.NewReader("{}"))
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Printf("response: %T\n", resp)
fmt.Printf("response.Body: %T\n", resp.Body)
data := make([]byte, 8)
for {
readN, err := resp.Body.Read(data)
if readN > 0 {
fmt.Print(string(data[:readN]))
}
if err == io.EOF {
break
}
if err != nil {
panic(err)
}
}
fmt.Println("done")
}
$ go run main.go
response: *http.Response
response.Body: *http.bodyEOFSignal
chunk [00]: 2021-04-29 17:31:24.273468827 +0800 CST m=+4985.717902553(动态输出)
chunk [01]: 2021-04-29 17:31:25.273744003 +0800 CST m=+4986.718177789
...
done
或者:
package main
import (
"bufio"
"fmt"
"io"
"net/http"
"strings"
)
func main() {
resp, err := http.Post("http://127.0.0.1:9080/", "application/json", strings.NewReader("{}"))
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Printf("response: %T\n", resp)
fmt.Printf("response.Body: %T\n", resp.Body)
reader := bufio.NewReader(resp.Body)
for {
line, err := reader.ReadBytes('\n')
if len(line) > 0 {
fmt.Print(string(line))
}
if err == io.EOF {
break
}
if err != nil {
panic(err)
}
}
fmt.Println("done")
}
$ go run main.go
response: *http.Response
response.Body: *http.bodyEOFSignal
chunk [00]: 2021-04-29 17:33:26.2627803 +0800 CST m=+5107.707214016(动态输出)
chunk [01]: 2021-04-29 17:33:27.262996851 +0800 CST m=+5108.707430602
...
done
不正确的写法:客户端无法动态输出,必须等到chunked结束后才输出:
package main
import (
"fmt"
"io/ioutil"
"net/http"
"strings"
)
func main() {
resp, err := http.Post("http://127.0.0.1:9080/", "application/json", strings.NewReader("{}"))
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Printf("response: %T\n", resp)
fmt.Printf("response.Body: %T\n", resp.Body)
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
fmt.Println(string(data))
}
原因:
客户端使用ioutil.ReadAll读取应答,而ioutil.ReadAll读到EOF才结束返回调用,输出终端。
Body.Read已经自动 decode chunk。
Body.Read仅当读到 chunk 0时,才返回EOF(ioutil.ReadAll才结束调用)。