英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论