douliang1891 2019-02-23 16:56
浏览 20
已采纳

我应该如何在Go中重用流?

I have a struct Artifact and the following two functions of interest:

type Artifact struct {
    Name string
    ZipFile io.ReadWriter
}

func New(name string, files []string, zipArchiveStream io.ReadWriter) *Artifact {}
func (a *Artifact) Upload() error {}

So here's the problem: before passing that io.ReadWriter around, I was using the file name. There are three operations I need to do with the zip file:

  1. Add the necessary files to it (i.e. Write)
  2. Re-read it to calculate the SHA256 sum (i.e. Seek, Read)
  3. Upload it to an S3 bucket (i.e. Seek, Read)

Well so before, when using the file name, I opened, closed, re-opened etc. for every operation. I started writing the unit tests however, and I realized my code was not really testable so I decided I would use io.ReadWriter so I could open files in real code usage, and pass buffers in testing.

The problem right now is that after the stream is read, its internal pointer needs to be reset in order to perform a second read (i.e. calculating the checksum, then uploading), but as far as I have read, streams cannot be rewinded. How should I approach this problem? because it seems like some is conceptually wrong with my current approach.

  • 写回答

1条回答 默认 最新

  • douyun3799 2019-02-23 17:13
    关注

    Did you consider using the io.ReadWriteSeeker interface instead?

    bytes.Reader implements Seek

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。