Skip to content

Commit

Permalink
svc: support closing via context (#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
jehiah authored Dec 1, 2020
1 parent d83e900 commit 979863f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
12 changes: 11 additions & 1 deletion svc/svc.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package svc

import "os/signal"
import (
"context"
"os/signal"
)

// Create variable signal.Notify function so we can mock it in tests
var signalNotify = signal.Notify
Expand All @@ -27,6 +30,13 @@ type Service interface {
Stop() error
}

// Context interface contains an optional Context function which a Service can implement.
// When implemented the context.Done() channel will be used in addition to signal handling
// to exit a process.
type Context interface {
Context() context.Context
}

// Environment contains information about the environment
// your application is running in.
type Environment interface {
Expand Down
13 changes: 11 additions & 2 deletions svc/svc_other.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (

// Run runs your Service.
//
// Run will block until one of the signals specified in sig is received.
// Run will block until one of the signals specified in sig is received or a provided context is done.
// If sig is empty syscall.SIGINT and syscall.SIGTERM are used by default.
func Run(service Service, sig ...os.Signal) error {
env := environment{}
Expand All @@ -27,7 +27,16 @@ func Run(service Service, sig ...os.Signal) error {

signalChan := make(chan os.Signal, 1)
signalNotify(signalChan, sig...)
<-signalChan

var doneChan <-chan struct{}
if s, ok := service.(Context); ok {
doneChan = s.Context().Done()
}

select {
case <-signalChan:
case <-doneChan:
}

return service.Stop()
}
Expand Down

0 comments on commit 979863f

Please sign in to comment.