Created
July 30, 2022 22:06
-
-
Save nkreiger/d957324f7c2cc4a76d207e0c113d74f4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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