|
| 1 | +package goa |
| 2 | + |
| 3 | +import ( |
| 4 | + "io" |
| 5 | + "sync" |
| 6 | + "sync/atomic" |
| 7 | +) |
| 8 | + |
| 9 | +// SkipResponseWriter converts an io.WriterTo into a io.ReadCloser. |
| 10 | +// The Read/Close methods this function returns will pipe the Write calls that wt makes, to implement a Reader that has the written bytes. |
| 11 | +// If Read is called Close must also be called to avoid leaking memory. |
| 12 | +// The returned value implements io.WriterTo as well, so the generated handler will call that instead of the Read method. |
| 13 | +// |
| 14 | +// Server handlers that use SkipResponseBodyEncodeDecode() io.ReadCloser as a return type. |
| 15 | +func SkipResponseWriter(wt io.WriterTo) io.ReadCloser { |
| 16 | + return &writerToReaderAdapter{WriterTo: wt} |
| 17 | +} |
| 18 | + |
| 19 | +type writerToReaderAdapter struct { |
| 20 | + io.WriterTo |
| 21 | + prOnce sync.Once |
| 22 | + pr *io.PipeReader |
| 23 | +} |
| 24 | + |
| 25 | +func (a *writerToReaderAdapter) initPipe() { |
| 26 | + r, w := io.Pipe() |
| 27 | + go func() { |
| 28 | + _, err := a.WriteTo(w) |
| 29 | + w.CloseWithError(err) |
| 30 | + }() |
| 31 | + a.pr = r |
| 32 | +} |
| 33 | + |
| 34 | +func (a *writerToReaderAdapter) Read(b []byte) (n int, err error) { |
| 35 | + a.prOnce.Do(a.initPipe) |
| 36 | + return a.pr.Read(b) |
| 37 | +} |
| 38 | + |
| 39 | +func (a *writerToReaderAdapter) Close() error { |
| 40 | + a.prOnce.Do(a.initPipe) |
| 41 | + return a.pr.Close() |
| 42 | +} |
| 43 | + |
| 44 | +type writeCounter struct { |
| 45 | + io.Writer |
| 46 | + n atomic.Int64 |
| 47 | +} |
| 48 | + |
| 49 | +func (wc *writeCounter) Count() int64 { return wc.n.Load() } |
| 50 | +func (wc *writeCounter) Write(b []byte) (n int, err error) { |
| 51 | + n, err = wc.Writer.Write(b) |
| 52 | + wc.n.Add(int64(n)) |
| 53 | + return |
| 54 | +} |
| 55 | + |
| 56 | +// WriterToFunc impelments [io.WriterTo]. The io.Writer passed to the function will be wrapped. |
| 57 | +type WriterToFunc func(w io.Writer) (err error) |
| 58 | + |
| 59 | +// WriteTo writes to w. |
| 60 | +// |
| 61 | +// The value in w is wrapped when passed to fn keeping track of how bytes are written by fn. |
| 62 | +func (fn WriterToFunc) WriteTo(w io.Writer) (n int64, err error) { |
| 63 | + wc := writeCounter{Writer: w} |
| 64 | + err = fn(&wc) |
| 65 | + return wc.Count(), err |
| 66 | +} |
0 commit comments