graceful

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Jul 19, 2022 License: Apache-2.0 Imports: 8 Imported by: 95

README

graceful

Build Status Coverage Status

Best practice http server configurations and helpers for Go 1.8's http graceful shutdown feature. Currently supports best practice configurations by:

Usage

To install this library, do:

go get github.com/ory/graceful
Running Cloudflare Config with Graceful Shutdown
package main

import (
    "net/http"
    "log"

    "github.com/ory/graceful"
)

func main() {
    server := graceful.WithDefaults(&http.Server{
        Addr: ":54932",
        // Handler: someHandler,
    })

    log.Println("main: Starting the server")
    if err := graceful.Graceful(server.ListenAndServe, server.Shutdown); err != nil {
        log.Fatalln("main: Failed to gracefully shutdown")
    }
    log.Println("main: Server was shutdown gracefully")
}

Documentation

Overview

Package graceful contains best practice http server configurations and helpers for Go 1.8's http graceful shutdown feature.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// DefaultCurvePreferences defines the recommended elliptic curves for modern TLS
	DefaultCurvePreferences = []tls.CurveID{
		tls.CurveP256,
		tls.X25519,
	}

	// DefaultCipherSuites defines the recommended cipher suites for modern TLS
	DefaultCipherSuites = []uint16{
		tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
		tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
		tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
		tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
		tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
		tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
	}

	// DefaultMinVersion defines the recommended minimum version to use for the TLS protocol (1.2)
	DefaultMinVersion uint16 = tls.VersionTLS12

	// DefaultReadTimeout sets the maximum time a client has to fully stream a request (5s)
	DefaultReadTimeout = 5 * time.Second
	// DefaultWriteTimeout sets the maximum amount of time a handler has to fully process a request (10s)
	DefaultWriteTimeout = 10 * time.Second
	// DefaultIdleTimeout sets the maximum amount of time a Keep-Alive connection can remain idle before
	// being recycled (120s)
	DefaultIdleTimeout = 120 * time.Second
	// DefaultReadHeaderTimeout sets the maximum amount of time a client has to fully stream a request header (5s)
	DefaultReadHeaderTimeout = DefaultReadTimeout
)
View Source
var DefaultShutdownTimeout = 5 * time.Second

DefaultShutdownTimeout defines how long Graceful will wait before forcibly shutting down

Functions

func Graceful added in v0.1.0

func Graceful(start StartFunc, shutdown ShutdownFunc) error

Graceful sets up graceful handling of SIGINT and SIGTERM, typically for an HTTP server. When signal is trapped, the shutdown handler will be invoked with a context that expires after DefaultShutdownTimeout (5s).

  server := graceful.WithDefaults(http.Server{})

  if err := graceful.Graceful(server.ListenAndServe, server.Shutdown); err != nil {
	   log.Fatal("Failed to gracefully shut down")
  }
Example
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"syscall"
	"time"

	"github.com/ory/graceful"
)

func main() {
	server := graceful.WithDefaults(&http.Server{
		Addr: "localhost:8080",
		Handler: http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
			fmt.Println("handler: Received the request")
			time.Sleep(3 * time.Second)

			fmt.Println("handler: Fulfilling the request after 3 seconds")
			fmt.Fprint(rw, "Hello World!")
		}),
	})

	// Kill the server after 5 seconds
	go func() {
		time.Sleep(2 * time.Second)
		fmt.Println("human: Killing the server after 2 seconds")
		syscall.Kill(syscall.Getpid(), syscall.SIGINT)
	}()

	// Start the server
	done := make(chan struct{})
	go func() {
		fmt.Println("graceful: Starting the server")
		if err := graceful.Graceful(server.ListenAndServe, server.Shutdown); err != nil {
			fmt.Println("graceful: Failed to gracefully shutdown")
			os.Exit(-1)
		}
		fmt.Println("graceful: Server was shutdown gracefully")

		done <- struct{}{}
	}()

	time.Sleep(1 * time.Second) // Give the server time to start up

	fmt.Println("main: Sending request")
	res, _ := http.Get("http://localhost:8080/")
	body, _ := ioutil.ReadAll(res.Body)
	fmt.Println("main: Received response ->", string(body))

	<-done

}
Output:

graceful: Starting the server
main: Sending request
handler: Received the request
human: Killing the server after 2 seconds
handler: Fulfilling the request after 3 seconds
main: Received response -> Hello World!
graceful: Server was shutdown gracefully

func WithDefaults added in v0.1.0

func WithDefaults(srv *http.Server) *http.Server

WithDefaults patches a http.Server based on a best practice configuration from Cloudflare: https://blog.cloudflare.com/exposing-go-on-the-internet/

You can override the defaults by mutating the Default* variables exposed by this package

Types

type ShutdownFunc added in v0.1.0

type ShutdownFunc func(context.Context) error

ShutdownFunc is the type of the function invoked by Graceful to shutdown the server

type StartFunc added in v0.1.0

type StartFunc func() error

StarFunc is the type of the function invoked by Graceful to start the server

Jump to

Keyboard shortcuts

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