Skip to content

Instantly share code, notes, and snippets.

@nkreiger
Created July 30, 2022 22:06
Show Gist options
  • Save nkreiger/d957324f7c2cc4a76d207e0c113d74f4 to your computer and use it in GitHub Desktop.
Save nkreiger/d957324f7c2cc4a76d207e0c113d74f4 to your computer and use it in GitHub Desktop.
import (
"github.com/joomcode/errorx"
"sync"
)
// Merge fans multiple error channels in to a single error channel
func Merge(errChans ...<-chan error) <-chan error {
mergedChan := make(chan error)
var errors []error
// Create a WaitGroup that waits for all of the errChans to close
var wg sync.WaitGroup
wg.Add(len(errChans))
go func() {
// When all of the errChans are closed, close the mergedChan
wg.Wait()
if len(errors) != 0 {
mergedChan <- errorx.WrapMany(errorx.InternalError, "internal error processing requests", errors...)
}
close(mergedChan)
}()
for i := range errChans {
go func(errChan <-chan error) {
// Wait for each errChan to close
for err := range errChan {
if err != nil {
// Fan the contents of each errChan into the mergedChan
// mergedChan <- err
errors = append(errors, err)
}
}
// Tell the WaitGroup that one of the errChans is closed
wg.Done()
}(errChans[i])
}
return mergedChan
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment