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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?