Gracefully Shutdown Webserver in Golang

Gracefully shutdown the server on signal of SIGTERM and SIGINT syscall#

In this post we will check for signals receive from user like terminate and interrupt using system calls and then gracefully shutdown our web server

syscall package from golang have many predefined system calls . we are using Interrupt and Terminate signal

there is a package signal.Notify() in golang which listen for signal from command prompt

it will listen and send signal over os.Signal chan type

for gracefully shutdown our server we have to use Server struct for creating server

we will also use NewServerMux() for attaching handlers

complete code will look like below one

package main

import (
	"context"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"syscall"
)

func main() {

	sig := make(chan os.Signal, 1)
	done := make(chan bool)
	signal.Notify(sig, syscall.SIGTERM, syscall.SIGINT)

	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Hello from server"))
	})
	server := http.Server{Addr: ":3000", Handler: mux}
	go func() {

		err := server.ListenAndServe()
		if err != nil {
			fmt.Println()
		}

	}()
	go func() {
		<-sig
		fmt.Println("Closing the server gracefully")
		server.Shutdown(context.Background())
		// After closing send singnal to done channel 
		done <- true
	}()
	<-done
	// After recieve singla it will close the main thread
	fmt.Println("Server Closed")

}



we have started our server in separate goroutine because ListenAndServe() is blocking method

And in seperate goroutine we have written logic for listening system call <-sig channel will block the seperate goroutine and will trigger next code execution when it will recieve syscall on press of Ctrl+C on terminal

signal.Notify() will recieve signal from terminal and send over sig channel and the our server.Shutdown() will be executed and that Shutdown() function gracefully shutdown our server

that’s all the logic behind the gracefully shutting down our server

After running program try to press Ctrl+C and see how it will terminate

comments powered by Disqus