Code maintenance: HTTP proxy loop reworked

- Blocking method calls on loop
- Restart proxy when settings change
- Detect server crash error and restart it
This commit is contained in:
Quentin McGaw
2020-12-30 18:44:46 +00:00
parent e827079604
commit 6f3a074e00
4 changed files with 177 additions and 85 deletions

View File

@@ -10,7 +10,7 @@ import (
)
type Server interface {
Run(ctx context.Context, wg *sync.WaitGroup)
Run(ctx context.Context, wg *sync.WaitGroup, errorCh chan<- error)
}
type server struct {
@@ -31,13 +31,13 @@ func New(ctx context.Context, address string, logger logging.Logger,
}
}
func (s *server) Run(ctx context.Context, wg *sync.WaitGroup) {
func (s *server) Run(ctx context.Context, wg *sync.WaitGroup, errorCh chan<- error) {
defer wg.Done()
server := http.Server{Addr: s.address, Handler: s.handler}
go func() {
<-ctx.Done()
s.logger.Warn("context canceled: exiting loop")
defer s.logger.Warn("loop exited")
s.logger.Warn("shutting down server")
defer s.logger.Warn("server shut down")
const shutdownGraceDuration = 2 * time.Second
shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownGraceDuration)
defer cancel()
@@ -47,8 +47,8 @@ func (s *server) Run(ctx context.Context, wg *sync.WaitGroup) {
}()
s.logger.Info("listening on %s", s.address)
err := server.ListenAndServe()
if err != nil && ctx.Err() != context.Canceled {
s.logger.Error(err)
if err != nil && ctx.Err() == nil {
errorCh <- err
}
s.internalWG.Wait()
}