Go:http Transfer-Encoding chunked 实时读写

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才结束调用)。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值