古老的榕树

优雅地关闭 Go HTTP 服务

潘军杰 发表于 2018-01-11 11:51 阅读(5398) 评论(0) 赞(1)

Go 1.8 之后,http.Server 增加了 Shutdown 函数,类似于第三方的 graceful 插件一样,可以平滑的关闭自身 HTTP 服务了,我们看看代码:


package main

import (
	"context"
	"github.com/urfave/negroni"
	"log"
	"net/http"
	"os"
	"os/signal"
	"time"
)


func main(){
    mux := http.NewServeMux()
    mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
      fmt.Fprintf(w, "Welcome to the home page!")
    })

    n := negroni.Classic()
    n.UseHandler(mux)

	srv := &http.Server{
		Addr:           ":3000",
		Handler:        n,
		ReadTimeout:    time.Second * 15,
		WriteTimeout:   time.Second * 15,
		IdleTimeout:    time.Second * 60,
		MaxHeaderBytes: 1 << 20,
	}

	go func() {
		if err := srv.ListenAndServe(); err != nil {
			log.Fatalf("listen and serve http server fail:\n %s\n", err)
		}
	}()

	exit := make(chan os.Signal, 1)
	signal.Notify(exit, os.Interrupt)
	<-exit 
	log.Println("it will shut down.")

	ctx, _ := context.WithTimeout(context.Background(), time.Second*15)
	err := srv.Shutdown(ctx)
	log.Println("it shutting down.\n", err)

	os.Exit(0)
}


标签: Go Shutdown graceful
0 条网友评论

哇~~~ 竟然还没有评论!

称呼*
邮箱*
内容*
验证码*
验证码 看不清换张