Graceful 是一个 Go 包,可实现 http.Handler 服务器的优雅关闭。
graceful() (http://godoc.org/GitHub.com/tylerb/graceful) (https://travis-ci.org/tylerb/graceful) (https://coveralls.io/r/tylerb/graceful) (https://gitter.im/tylerb/graceful?utmsource=badge&utmmedium=badge&utmcampaign=pr-badge) ========== Graceful 是一个 Go 1.3+ 包,可实现 http.Handler 服务器的优雅关闭。如果您使用 Go 1.8,则可能不需要使用此库!请考虑使用 http.Server 的内置 Shutdown() 方法进行优雅关闭。安装 要安装,只需执行: go get gopkg.in/tylerb/graceful.v1 我使用 gopkg.in 来控制版本。使用 Graceful 很简单。只需创建 http.Handler 并将其传递给 Run 函数: go package main import ( "gopkg.in/tylerb/graceful.v1" "net/http" "fmt" "time" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, req http.Request) { fmt.Fprintf(w, "Welcome to the home page!") }) graceful.Run(":3001",10time.Second,mux) } 另一个示例,使用 Negroni,其功能大致相同: go package main import ( "GitHub.com/codegangsta/negroni" "gopkg.in/tylerb/graceful.v1" "net/http" "fmt" "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) //n.Run(":3000") graceful.Run(":3001",10time.Second,n) } 除了 Run 之外,还有 http.Server 的对应函数 ListenAndServe、ListenAndServeTLS 和 Serve,它们允许您配置 HTTPS、自定义超时和错误处理。Graceful 还可以通过直接实例化其 Server 类型来使用,其中包含一个 http.Server: go mux := // ... srv := &graceful.Server{ Timeout: 10 time.Second, Server: &http.Server{ Addr: ":1234", Handler: mux, }, } srv.ListenAndServe() 这种形式允许您设置 ConnState 回调,其工作方式与 http.Server 中的回调相同: go mux := // ... srv := &graceful.Server{ Timeout: 10 time.Second, ConnState: func(conn net.Conn, state http.ConnState) { // conn 具有新的状态 }, Server: &http.Server{ Addr: ":1234", Handler: mux, }, } srv.ListenAndServe() 行为 当 Graceful 接收到 SIGINT 或 SIGTERM 信号时…
暂无开放 Issues,或尚未同步最近议题。