shutdown

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 21, 2019 License: Apache-2.0 Imports: 6 Imported by: 1

Documentation

Overview

Package shutdown makes it easy to add graceful shutdown to your application

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func StartSafeServer

func StartSafeServer(server *http.Server, livenessMarkerPath string) error

StartSafeServer wraps the server to shutdown gracefully. This implementation handles SIGINT and SIGTERM cleanly. Pass in your *http.Server which will be started for you. Second, pass in a path for where your liveness marker file should live. This can be used by your Kubernetes liveness probe to see whether the server has started. We will create a file at that location right before the server starts and we will delete the file right after the server shutsdown. This lets you decouple the requirement for http traffic to be routable to the service in order to figure out if the application process has been stopped.

Implementation heavily inspired by:

https://medium.com/over-engineering/graceful-shutdown-with-go-http-servers-and-kubernetes-rolling-updates-6697e7db17cf

Example
package main

import (
	"log"
	"net/http"
	"time"

	"github.com/abatilo/go-kube-shutdown/pkg/shutdown"
)

func main() {
	// Use a default router for serving requests
	router := http.NewServeMux()

	// Simulate a long running request
	router.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {
		<-time.After(time.Second * 5)
		w.Write([]byte("pong"))
	})

	server := &http.Server{
		Addr:    ":9090",
		Handler: router,
	}

	log.Printf("Starting a server that will shutdown safely")
	livenessFileMarker := "/tmp/liveness"
	err := shutdown.StartSafeServer(server, livenessFileMarker)
	if err != http.ErrServerClosed {
		log.Printf("Server did not shutdown cleanly: %v", err)
	}
	log.Printf("Connections have drained from the server and the server has shutdown")
}
Output:

Types

This section is empty.

Jump to

Keyboard shortcuts

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