Skip to content

Instantly share code, notes, and snippets.

@nrjpoddar
Created July 3, 2019 21:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nrjpoddar/5b5508eb39638b0a7146975f0e535988 to your computer and use it in GitHub Desktop.
Save nrjpoddar/5b5508eb39638b0a7146975f0e535988 to your computer and use it in GitHub Desktop.
Safe error handling from multiple Go routines via buffered channels
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