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

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

报告相同问题?