Skip to content

Commit

Permalink
Some later refactorings
Browse files Browse the repository at this point in the history
  • Loading branch information
lionelbarrow committed Dec 20, 2013
1 parent 69f78b1 commit 795a20d
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 19 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Manners allows you to shut your Go webserver down gracefully, without dropping a

```go
func main() {
handler = MyHTTPHandler()
handler := MyHTTPHandler()
signal.Notify(manners.ShutdownChannel)
manners.ListenAndServe(handler, ":7000")
}
Expand Down
6 changes: 2 additions & 4 deletions listener.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
package manners

import (
"net"
)
import "net"

// A GracefulListener differs from a standard net.Listener in three ways:
// 1. It increases the server's WaitGroup when it accepts a connection.
// 2. It returns GracefulConnections rather than normal net.Conns.
// 3. If Accept() is called after it is gracefully closed, it returns a
// 3. If Accept() is called after it is gracefully closed, it returns a
// listenerAlreadyClosed error. The GracefulServer will ignore this
// error.
type GracefulListener struct {
Expand Down
25 changes: 11 additions & 14 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@ import (
)

func NewServer() *GracefulServer {
return &GracefulServer{
shutdown: make(chan bool),
}
return &GracefulServer{
shutdown: make(chan bool),
}
}

type GracefulServer struct {
wg sync.WaitGroup
shutdown chan bool
shutdownHandler func() error
shutdownHandler func()
}

func (s *GracefulServer) ListenAndServe(addr string, handler http.Handler) error {
Expand All @@ -29,8 +29,8 @@ func (s *GracefulServer) ListenAndServe(addr string, handler http.Handler) error
}

func (s *GracefulServer) Serve(listener *GracefulListener, handler http.Handler) error {
s.shutdownHandler = func() error { return listener.Close() }
s.WaitForShutdown()
s.shutdownHandler = func() { listener.Close() }
s.listenForShutdown()
server := http.Server{Handler: handler}
err := server.Serve(listener)
if err == nil {
Expand All @@ -49,12 +49,9 @@ func (s *GracefulServer) FinishRoutine() {
s.wg.Done()
}

func (s *GracefulServer) WaitForShutdown() chan error {
errs := make(chan error)
go func() {
<-s.shutdown
err := s.shutdownHandler()
errs <-err
}()
return errs
func (s *GracefulServer) listenForShutdown() {
go func() {
<-s.shutdown
s.shutdownHandler()
}()
}

0 comments on commit 795a20d

Please sign in to comment.