graceful

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2025 License: Apache-2.0 Imports: 5 Imported by: 0

README

graceful

graceful is a package to apply graceful shutdown for Go projects. It provides cleanup option to cleaning something while shutting down the server.

Installation

go get github.com/gozeloglu/graceful

Example

package main

import (
	"database/sql"
	"log"
	"net/http"
	"os"
	"syscall"
	"time"

	"github.com/gozeloglu/graceful"
)

func main() {
	db := sql.DB{}
	f := os.File{}
	srv := &http.Server{}

	// Create cleanup functions
	dbCleanUpFunc := func() {
		db.Close()
	}
	fileCleanUpFunc := func() {
		f.Close()
	}

	g := &graceful.Graceful{}
	g.RegisterCleanupFunctions(dbCleanUpFunc, fileCleanUpFunc)
	err := g.Shutdown(srv, 5*time.Second, os.Interrupt, syscall.SIGTERM)
	if err != nil {
		log.Fatal(err)
	}
}

LICENSE

Apache License

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CleanUpFunc

type CleanUpFunc func()

CleanUpFunc is a type for batch cleanups. It should be given to Graceful.RegisterCleanupFunctions method.

type Graceful

type Graceful struct {
	// contains filtered or unexported fields
}

Graceful type for registering cleanup functions and graceful shutdown. You can define as in the example below.

Example:

g := &Graceful{}

func (*Graceful) RegisterCleanupFunctions

func (g *Graceful) RegisterCleanupFunctions(functions ...CleanUpFunc)

RegisterCleanupFunctions registers cleanup functions. You can pass the functions that should be cleaned up after graceful shutdown. They can be closing database, file, or even context cancelling.

func (*Graceful) Shutdown

func (g *Graceful) Shutdown(srv *http.Server, timeout time.Duration, signals ...os.Signal) error

Shutdown listens given os signals. If any of them is triggered, the given http.Server is shutdown. Finally, all cleanup functions are triggered after the http.Server is shutdown. If no signal is passed to method, it means that all signals are listened. Graceful.Shutdown blocks the code until notified by any given signal.

Example:

srv := &http.Server{}
dbCleanUpFunc := func() {
	db.Close()
}
fileCleanUpFunc := func() {
	f.Close()
}
g := &Graceful{}
g.RegisterCleanupFunctions(dbCleanUpFunc, fileCleanUpFunc)
g.Shutdown(srv, 5*time.Second, os.Interrupt, syscall.SIGTERM)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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