Golang优雅退出http server

最近经常听到“优雅”二字,很多人在谈代码的优雅。又碰巧看到了一段golang http server的“优雅”代码,大家共欣赏。

package main

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

func main() {
	http.Handle("/", http.FileServer(http.Dir(".")))

	server := &http.Server{
		Addr:    ":4040",
		Handler: http.DefaultServeMux,
	}

	quitChan := make(chan os.Signal)
	signal.Notify(quitChan,
		syscall.SIGINT,
		syscall.SIGTERM,
		syscall.SIGHUP,
	)

	go func() {
		fmt.Println(<-quitChan)
		server.Close()
	}()

	go server.ListenAndServe()

	time.Sleep(2 * time.Second)

	quitChan <- syscall.SIGINT

	time.Sleep(1 * time.Second)
}

这里说的优雅,就是主动接收“退出信号”,关闭服务。

你可能感兴趣的:(------【golang】,☀编程语言,golang)