Add sync.WaitGroup for proper error handling in Run()

This commit is contained in:
Herman Slatman 2021-03-26 16:21:02 +01:00
parent 9bda3c465a
commit 2320d0911e
No known key found for this signature in database
GPG key ID: F4D8A44EA0A75A4F

View file

@ -8,6 +8,7 @@ import (
"net/http" "net/http"
"net/url" "net/url"
"reflect" "reflect"
"sync"
"github.com/go-chi/chi" "github.com/go-chi/chi"
"github.com/pkg/errors" "github.com/pkg/errors"
@ -238,18 +239,28 @@ func (ca *CA) Init(config *authority.Config) (*CA, error) {
// Run starts the CA calling to the server ListenAndServe method. // Run starts the CA calling to the server ListenAndServe method.
func (ca *CA) Run() error { func (ca *CA) Run() error {
var wg sync.WaitGroup
errors := make(chan error, 1) errors := make(chan error, 1)
go func() {
if ca.insecureSrv != nil { if ca.insecureSrv != nil {
wg.Add(1)
go func() {
defer wg.Done()
errors <- ca.insecureSrv.ListenAndServe() errors <- ca.insecureSrv.ListenAndServe()
} }()
}() }
wg.Add(1)
go func() { go func() {
defer wg.Done()
errors <- ca.srv.ListenAndServe() errors <- ca.srv.ListenAndServe()
}() }()
// wait till error occurs; ensures the servers keep listening // wait till error occurs; ensures the servers keep listening
err := <-errors err := <-errors
wg.Wait()
return err return err
} }