提问人:Alicia Wentworth 提问时间:10/15/2023 更新时间:10/15/2023 访问量:44
使用 IO。SectionReader 和错误处理混乱
using io.SectionReader and error handling clutter
问:
我正在编写一些东西,它获取一个文件并读取文件的标头(前 48 个字节)(我们自己 1995 年的愚蠢格式),其中包含 6 个偏移量(以及其他元数据),然后我寻求这些偏移量以读取特定于我们域的数据,然后最后拉取文件的最后 16 个字节来读取校验和(各种)。
我的代码正在使用 io。SectionReader 和(在简单的层面上)如下所示:
const PackHeaderSize = 48
const PackFooterSize = 16
packedHeader := make([]byte, PackHeaderSize)
sr.Seek(0, io.SeekStart)
sr.Read(packedHeader)
// Do some decoding of packedHeader to get the offsets into an array
// ChunkSize varies based on the PackedHeader meta data
// Data is written to a Crc32 Hash
for i := 0; i < offsets; i++ {
chunk := make([]byte, ChunkSize)
sr.Seek(offset, io.SeekCurrent)
sr.Read(chunk)
crc.Write(chunk)
}
footer := make([]byte, PackFooterSize)
sr.Read(footer)
// Compare footer CRC with the crc computed value
我还是很新手,但似乎我必须检查每个 sr 中的错误。寻求和sr。读取,这给出了很多冗长的代码。有没有更好的方法来写上面的内容?
我试图将它们放入单独的函数中,但代码变得非常混乱。原版是用 C 语言编写的(在 1989 年或 90 年),非常冗长(因为他们通过读取每个字节来计算校验和 - 而不是 CRC,其他东西)。
如何以一种 golang 方式从一个数组流式传输到另一个数组,或者以优雅的方式处理错误?
答: 暂无答案
评论