From 7ee3209a2f1be62521f6bc2e770ce2c18ffda00f Mon Sep 17 00:00:00 2001 From: whywaita Date: Thu, 3 Jun 2021 18:47:25 +0900 Subject: [PATCH] handling error using context.Context --- cmd/server/cmd.go | 2 +- pkg/runner/runner.go | 4 +++- pkg/starter/starter.go | 3 +++ pkg/web/http.go | 26 ++++++++++++++++++++------ 4 files changed, 27 insertions(+), 8 deletions(-) diff --git a/cmd/server/cmd.go b/cmd/server/cmd.go index a96f78e..689a6be 100644 --- a/cmd/server/cmd.go +++ b/cmd/server/cmd.go @@ -62,7 +62,7 @@ func (m *myShoes) Run() error { ctx := context.Background() eg.Go(func() error { - if err := web.Serve(m.ds); err != nil { + if err := web.Serve(ctx, m.ds); err != nil { return fmt.Errorf("failed to serve: %w", err) } return nil diff --git a/pkg/runner/runner.go b/pkg/runner/runner.go index 1bbecc0..50016b8 100644 --- a/pkg/runner/runner.go +++ b/pkg/runner/runner.go @@ -59,11 +59,13 @@ func (m *Manager) Loop(ctx context.Context) error { if err := m.doTargetToken(ctx); err != nil { logger.Logf(false, "failed to refresh token: %+v", err) } - case <-ticker.C: if err := m.do(ctx); err != nil { logger.Logf(false, "failed to starter: %+v", err) } + + case <-ctx.Done(): + return nil } } } diff --git a/pkg/starter/starter.go b/pkg/starter/starter.go index 16040c4..5b16b43 100644 --- a/pkg/starter/starter.go +++ b/pkg/starter/starter.go @@ -49,6 +49,9 @@ func (s *Starter) Loop(ctx context.Context) error { if err := s.do(ctx); err != nil { logger.Logf(false, "failed to starter: %+v", err) } + + case <-ctx.Done(): + return nil } } } diff --git a/pkg/web/http.go b/pkg/web/http.go index 76c9c68..bb7904c 100644 --- a/pkg/web/http.go +++ b/pkg/web/http.go @@ -1,6 +1,7 @@ package web import ( + "context" "encoding/json" "fmt" "net/http" @@ -71,16 +72,29 @@ func NewMux(ds datastore.Datastore) *goji.Mux { } // Serve start webhook receiver -func Serve(ds datastore.Datastore) error { +func Serve(ctx context.Context, ds datastore.Datastore) error { mux := NewMux(ds) - listenAddress := fmt.Sprintf(":%d", config.Config.Port) - logger.Logf(false, "start webhook receiver, listen %s", listenAddress) - if err := http.ListenAndServe(listenAddress, mux); err != nil { - return fmt.Errorf("failed to listen and serve: %w", err) + s := &http.Server{ + Addr: listenAddress, + Handler: mux, } - return nil + errCh := make(chan error) + go func() { + defer close(errCh) + logger.Logf(false, "start webhook receiver, listen %s", listenAddress) + if err := s.ListenAndServe(); err != nil { + errCh <- fmt.Errorf("failed to listen and serve: %w", err) + } + }() + + select { + case <-ctx.Done(): + return s.Shutdown(ctx) + case err := <-errCh: + return fmt.Errorf("occured error in web serve: %w", err) + } } func apacheLogging(r *http.Request) {