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

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

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

问题

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

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

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

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

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

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

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

英文:

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

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

And then conservatively allocating a slice for the unzipped data.

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

And finally trimming the slice after reading

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

Is there a better way to do this ?

答案1

得分: 4

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

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

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

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

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

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

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

  1. buf := getBufferFromPool()
  2. 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:

确定