Created
July 3, 2019 21:48
-
-
Save nrjpoddar/5b5508eb39638b0a7146975f0e535988 to your computer and use it in GitHub Desktop.
Safe error handling from multiple Go routines via buffered channels
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
func (m *Factory) StartInformer() error { | |
// Stop channel for our informers | |
stopCh := make(chan struct{}) | |
// error channel for the go funcs | |
errCh := make(chan string, 2) | |
defer close(errCh) | |
// Synchronizing at the end | |
var wg sync.WaitGroup | |
wg.Add(2) | |
// k8s informer | |
go func() { | |
defer wg.Done() | |
m.K8s().Start(stopCh) | |
oks := m.K8s().WaitForCacheSync(stopCh) | |
// Check for any failure (not ok) | |
for inf, ok := range oks { | |
if !ok { | |
errCh <- fmt.Sprintf("Failed to sync k8s informer %s", inf) | |
break | |
} | |
} | |
}() | |
// istio informer | |
go func() { | |
defer wg.Done() | |
m.Istio().Start(stopCh) | |
oks := m.Istio().WaitForCacheSync(stopCh) | |
// Check for any failure (not ok) | |
for inf, ok := range oks { | |
if !ok { | |
errCh <- fmt.Sprintf("Failed to sync istio informer %s", inf) | |
break | |
} | |
} | |
}() | |
wg.Wait() | |
close(stopCh) | |
// Check error | |
select { | |
case err := <-errCh: | |
logs.Error(err) | |
return errors.New(err) | |
default: | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment