Skip to content

Commit

Permalink
added graceful shutdown support
Browse files Browse the repository at this point in the history
  • Loading branch information
qiangxue committed Jan 13, 2020
1 parent 4f4446e commit e09fe87
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ It has the following features:
* URL creation according to the predefined routes
* compatible with `http.Handler` and `http.HandlerFunc`
* ready-to-use handlers sufficient for building RESTful APIs
* graceful shutdown

If you are using [fasthttp](https://github.com/valyala/fasthttp), you may use a similar routing package [fasthttp-routing](https://github.com/qiangxue/fasthttp-routing) which is adapted from ozzo-routing.

Expand Down
7 changes: 7 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,13 @@ func (c *Context) Write(data interface{}) error {
return c.writer.Write(c.Response, data)
}

// WriteWithStatus sends the HTTP status code and writes the given data of arbitrary type to the response.
// See Write() for details on how data is written to response.
func (c *Context) WriteWithStatus(data interface{}, statusCode int) error {
c.Response.WriteHeader(statusCode)
return c.Write(data)
}

// SetDataWriter sets the data writer that will be used by Write().
func (c *Context) SetDataWriter(writer DataWriter) {
c.writer = writer
Expand Down
35 changes: 35 additions & 0 deletions graceful.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Copyright 2016 Qiang Xue. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package routing

import (
"context"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)

// GracefulShutdown shuts down the given HTTP server gracefully when receiving an os.Interrupt or syscall.SIGTERM signal.
// It will wait for the specified timeout to stop hanging HTTP handlers.
func GracefulShutdown(hs *http.Server, timeout time.Duration, logFunc func(format string, args ...interface{})) {
stop := make(chan os.Signal, 1)

signal.Notify(stop, os.Interrupt, syscall.SIGTERM)

<-stop

ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()

logFunc("shutting down server with %s timeout", timeout)

if err := hs.Shutdown(ctx); err != nil {
logFunc("error while shutting down server: %v", err)
} else {
logFunc("server was shut down gracefully")
}
}

0 comments on commit e09fe87

Please sign in to comment.