graceful

package module
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Jun 21, 2025 License: MIT Imports: 8 Imported by: 18

README

graceful

English | 繁體中文 | 简体中文

Run Tests codecov Go Report Card Go Reference

A lightweight Go package for graceful shutdown and job management. Easily manage long-running jobs and shutdown hooks, ensuring your services exit cleanly and predictably.


Table of Contents


Features

  • Graceful shutdown for Go services
  • Manage multiple running jobs with context cancellation
  • Register shutdown hooks for cleanup tasks
  • Custom logger support
  • Simple API, easy integration

Installation

go get github.com/appleboy/graceful

Usage

Add Running Jobs

Register long-running jobs that will be cancelled on shutdown:

package main

import (
  "context"
  "log"
  "time"

  "github.com/appleboy/graceful"
)

func main() {
  m := graceful.NewManager()

  // Add job 01
  m.AddRunningJob(func(ctx context.Context) error {
    for {
      select {
      case <-ctx.Done():
        return nil
      default:
        log.Println("working job 01")
        time.Sleep(1 * time.Second)
      }
    }
  })

  // Add job 02
  m.AddRunningJob(func(ctx context.Context) error {
    for {
      select {
      case <-ctx.Done():
        return nil
      default:
        log.Println("working job 02")
        time.Sleep(500 * time.Millisecond)
      }
    }
  })

  <-m.Done()
}
Add Shutdown Jobs

Register shutdown hooks to run cleanup logic before exit:

package main

import (
  "context"
  "log"
  "time"

  "github.com/appleboy/graceful"
)

func main() {
  m := graceful.NewManager()

  // Add running jobs (see above)

  // Add shutdown 01
  m.AddShutdownJob(func() error {
    log.Println("shutdown job 01 and wait 1 second")
    time.Sleep(1 * time.Second)
    return nil
  })

  // Add shutdown 02
  m.AddShutdownJob(func() error {
    log.Println("shutdown job 02 and wait 2 second")
    time.Sleep(2 * time.Second)
    return nil
  })

  <-m.Done()
}
Custom Logger

You can use your own logger (see zerolog example):

m := graceful.NewManager(
  graceful.WithLogger(logger{}),
)

Examples


License

MIT

Documentation

Overview

Package graceful provides a Logger implementation using Go's log/slog.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Logger

type Logger interface {
	Infof(format string, args ...interface{})
	Errorf(format string, args ...interface{})
}

Logger interface is used throughout gorush

func NewEmptyLogger

func NewEmptyLogger() Logger

NewEmptyLogger for simple logger.

func NewLogger

func NewLogger() Logger

NewLogger for simple logger.

func NewSlogLogger added in v1.2.0

func NewSlogLogger(opts ...SlogLoggerOption) Logger

NewSlogLogger creates a Logger using flexible option pattern.

Usage:

NewSlogLogger()                        // text mode (default)
NewSlogLogger(WithJSON())              // json mode
NewSlogLogger(WithSlog(loggerObj))     // inject custom *slog.Logger, which overrides other options

type Manager

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

Manager manages the graceful shutdown process

func GetManager

func GetManager() *Manager

NewManager get the Manager

func NewManager

func NewManager(opts ...Option) *Manager

NewManager initial the Manager

func NewManagerWithContext added in v0.0.2

func NewManagerWithContext(ctx context.Context, opts ...Option) *Manager

NewManagerWithContext initial the Manager with custom context

func (*Manager) AddRunningJob

func (g *Manager) AddRunningJob(f RunningJob)

AddRunningJob add running task

func (*Manager) AddShutdownJob added in v0.0.2

func (g *Manager) AddShutdownJob(f ShtdownJob)

AddShutdownJob add shutdown task

func (*Manager) Done

func (g *Manager) Done() <-chan struct{}

Done allows the manager to be viewed as a context.Context.

func (*Manager) ShutdownContext added in v0.0.4

func (g *Manager) ShutdownContext() context.Context

ShutdownContext returns a context.Context that is Done at shutdown

type Option

type Option interface {
	Apply(*Options)
}

Option interface for configuration.

func WithContext

func WithContext(ctx context.Context) Option

WithContext custom context

func WithLogger

func WithLogger(logger Logger) Option

WithLogger custom logger

type OptionFunc added in v0.1.0

type OptionFunc func(*Options)

OptionFunc is a function that configures a graceful shutdown.

func (OptionFunc) Apply added in v0.1.0

func (f OptionFunc) Apply(option *Options)

Apply calls f(option)

type Options added in v0.1.0

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

Options for graceful shutdown

type RunningJob

type RunningJob func(context.Context) error

type ShtdownJob added in v0.0.2

type ShtdownJob func() error

type SlogLoggerOption added in v1.2.0

type SlogLoggerOption func(*slogLoggerOptions)

SlogLoggerOption applies configuration to NewSlogLogger.

func WithJSON added in v1.2.0

func WithJSON() SlogLoggerOption

WithJSON returns an option to set output as JSON format.

func WithSlog added in v1.2.0

func WithSlog(logger *slog.Logger) SlogLoggerOption

WithSlog injects a custom *slog.Logger instance.

Jump to

Keyboard shortcuts

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