Golang优雅退出http server

来源:互联网 发布:黑帽seo劫持博客违法吗 编辑:程序博客网 时间:2024/06/07 21:49

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

package mainimport (    "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)}

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

0 0
原创粉丝点击