Skip to content

Commit

Permalink
handling error using context.Context
Browse files Browse the repository at this point in the history
  • Loading branch information
whywaita committed Jun 3, 2021
1 parent d1ce17c commit 7ee3209
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 8 deletions.
2 changes: 1 addition & 1 deletion cmd/server/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion pkg/runner/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
}
Expand Down
3 changes: 3 additions & 0 deletions pkg/starter/starter.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
}
Expand Down
26 changes: 20 additions & 6 deletions pkg/web/http.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package web

import (
"context"
"encoding/json"
"fmt"
"net/http"
Expand Down Expand Up @@ -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) {
Expand Down

0 comments on commit 7ee3209

Please sign in to comment.