从计算机科学的角度来看,lang http.Request Body是什么?

问题描述:

in http.Request type Body is closed when request is send by client. Why it need to be closed, why it can not be string, which you can read over and over?

http中的

。请求类型客户端发送请求时,主体将关闭。 为什么它需要关闭,为什么不能是字符串,您可以反复阅读? p> div>

This is called a stream. It's useful because it lets you handle data without having the whole set of data available in memory. It also lets you give the results of the operations you may do faster : you don't wait for the whole set to be computed.

As soon as you want to handle big data or worry about performances, you need streams.

It's also a convenient abstraction that lets you handle data one by one even when the whole set is available without having to handle an offset to iterate over the whole.

You can store the request stream as a string using the bytes and the io package:

func handler(w http.ResponseWriter, r *http.Request) {
    var bodyAsString string
    b := new(bytes.Buffer)

    _, err := io.Copy(b, r)
    if err == io.EOF {
        bodyAsString = b.String()
    }
}