有没有更好的方法将未压缩的数据读入切片中?

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

Is there a better way to read unzipped data into a slice?

问题

我正在从HTTP请求中读取gzip数据,代码如下:

gzr, err := gzip.NewReader(resp.Body)
handle(err)

然后为解压后的数据保守地分配一个切片。

cl := resp.Header.Get("Content-Length")
icl, err := strconv.Atoi(cl)
handle(err)
ubs := make([]byte, icl*3)

最后,在读取后修剪切片。

_, err = gzr.Read(ubs)
ubs = bytes.TrimRightFunc(ubs, sliceFunc)

有没有更好的方法来做这个?

英文:

I'm reading gzip data from a http request like this:

gzr, err := gzip.NewReader(resp.Body)
handle(err)

And then conservatively allocating a slice for the unzipped data.

cl := resp.Header.Get("Content-Length")
icl, err := strconv.Atoi(cl)
handle(err)
ubs := make([]byte, icl*3)

And finally trimming the slice after reading

_, err = gzr.Read(ubs)
ubs = bytes.TrimRightFunc(ubs, sliceFunc)

Is there a better way to do this ?

答案1

得分: 4

首先,.Read 返回读取的字节数,所以你可以这样做:

n, err = gzr.Read(ubs)
ubs = ubs[:n]

此外,你可以使用一个 bytes.Buffer 池,然后这样做:

buf := getBufferFromPool()
io.Copy(buf, gzr)
英文:

For starters, .Read returns the numbers of bytes read, so you can do something like:

n, err = gzr.Read(ubs)
ubs = ubs[:n]

Also you can use a bytes.Buffer pool and do something like:

buf := getBufferFromPool()
io.Copy(buf, gzr)

huangapple
  • 本文由 发表于 2015年8月28日 07:13:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/32260883.html
匿名

发表评论

匿名网友

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

确定