What is go lang http.Request Body in term of computer science?

huangapple go评论83阅读模式
英文:

What is go lang http.Request Body in term of computer science?

问题

在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?

答案1

得分: 7

这被称为“流”(stream)。它很有用,因为它允许你在没有整个数据集可用于内存的情况下处理数据。它还可以更快地提供操作的结果:你不需要等待整个集合被计算完毕。

一旦你想处理大数据或关注性能问题,你就需要使用流。

它还是一个方便的抽象,即使整个数据集可用,也可以逐个处理数据,而不需要处理偏移量来遍历整个数据集。

英文:

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.

答案2

得分: 2

你可以使用bytesio包将请求流存储为字符串:

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

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

以上代码将请求体作为字符串存储在bodyAsString变量中。

英文:

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()
    }
}

huangapple
  • 本文由 发表于 2013年10月10日 18:01:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/19292755.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定