graceful

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 30, 2022 License: MIT Imports: 8 Imported by: 0

README

graceful

Graceful Shutdown for your HTTP Server

This package provides a method to gracefully shutdown your golang http server.

When a SIGTERM signal is received, the shutdown method on your server is executed. That means that no new connections are accepted but all running requests continue until finished.

func main() {
    server := &http.Server{}

    if err := graceful.ListenAndServe(server); err != nil && err != http.ErrServerClosed {
        log.Println("Could not start server, error:", err.Error())
        os.Exit(1)
    }
}

Graceful Shutdown for your Go Routines

After shutting down your server you can wait for registered go routines to finish before exiting.

func main() {

    ...

    log.Println("Waiting for unfinished go routines...")
    graceful.Wait() // blocks until all go routines are finished
}

To keep track of your started go routines you need to start them like this (otherwise you can't wait for them):

graceful.Run(func() {
    // do not start a go routine on your own
    // the go routine will be started in the package to keep track of it
})

Middlewares for your Go Routines

It is possible to register middlewares that are applied automatically to all your go routines.

graceful.AddMiddleware(func(next func(context.Context)) func(context.Context) {
    return func(ctx context.Context) {
        // do something before your go routine
        next(ctx)
        // do something after your go routine
    }
})

For middlewares to be useful you should provide a context that is passed down to your function. The context is also available in all middlewares.

graceful.RunContext(context.Background(), func(ctx context.Context) {
    // do not start a go routine on your own
    // the go routine will be started in the package to keep track of it
})
Example: Middleware to trace Go Routines with OpenCensus
import (
	"github.com/mattrx/graceful"
	"go.opencensus.io/trace"
)

graceful.AddMiddleware(func(next func(context.Context)) func(context.Context) {
    return func(ctx context.Context) {
        ctx, span := trace.StartSpan(ctx, "go-routine")
        defer span.End()

        next(ctx)
    }
})
Example: Middleware to recover from Panics in Go Routines
import (
	"github.com/mattrx/graceful"
)

graceful.AddMiddleware(func(next func(context.Context)) func(context.Context) {
    return func(ctx context.Context) {
        defer func() {
            if err := recover(); err != nil {
                // handle panic as you see fit
            }
        }()

        next(ctx)
    }
})

Cleanup after Shutdown

After shutting down you may want to run some cleanup functions to close connections or flush some internal memory buffer. You can run them like this:

func main() {

    ...

    log.Println("Running cleanup functions...")
    graceful.Cleanup()
}

In your code you just have to register the functions when you get them:

db, err := sqlx.Connect("mysql", config.FormatDSN())

...

graceful.AddCleanup(func() {
    if err := db.Close(); err != nil {
        log.Printf("Error closing db conn: %v", err)
    }
})

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddCleanup

func AddCleanup(f func())

AddCleanup function to be executed when shutting down

func AddMiddleware

func AddMiddleware(mw middlewareFunc)

AddMiddleware to the stack

func Cleanup

func Cleanup()

Cleanup executes all registered cleanup functions

func ClearMiddlewares

func ClearMiddlewares()

ClearMiddlewares from the stack

func DisableDebugLogging

func DisableDebugLogging()

DisableDebugLogging removes the logger

func EnableDebugLogging

func EnableDebugLogging(logger logFunc)

EnableDebugLogging will print the file and line number for each started go routine

func ListenAndServe

func ListenAndServe(server *http.Server) error

ListenAndServe on the server with graceful shutdown

func Run

func Run(routine func())

Run a new tracked go routine

func RunContext

func RunContext(ctx context.Context, routine func(context.Context))

RunContext runs a new tracked go routine with a context

func Wait

func Wait()

Wait for all go routines to finish

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL