Go 1.8 http graceful 體驗

很高興Go 1.8發佈了,這是個值得慶祝的日子。golang

如何優雅的關閉http服務在Go Web開發中一直被說起和討論的話題,今天Go 1.8的發佈終於爲咱們帶來了這個特性。code

文檔中是這樣介紹的:server

func (srv *Server) Shutdown(ctx context.Context) error

Shutdown 將無中斷的關閉正在活躍的鏈接,而後平滑的中止服務。處理流程以下:開發

  • 首先關閉全部的監聽文檔

  • 而後關閉全部的空閒鏈接get

  • 而後無限期等待鏈接處理完畢轉爲空閒,並關閉it

  • 若是提供了 帶有超時的Context,將在服務關閉前返回 Context的超時錯誤import

須要注意的是,Shutdown 並不嘗試關閉或者等待 hijacked鏈接,如 WebSockets。若是須要的話調用者須要分別處理諸如長鏈接類型的等待和關閉。sed

其實,你只要調用 Shutdown 方法就行了。List

簡單示例:

// main.go

package main

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

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello World, %v\n", time.Now())
    })

    s := &http.Server{
        Addr:           ":8080",
        Handler:        http.DefaultServeMux,
        ReadTimeout:    10 * time.Second,
        WriteTimeout:   10 * time.Second,
        MaxHeaderBytes: 1 << 20,
    }

    go func() {
        log.Println(s.ListenAndServe())
        log.Println("server shutdown")
    }()

    // Handle SIGINT and SIGTERM.
    ch := make(chan os.Signal)
    signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
    log.Println(<-ch)

    // Stop the service gracefully.
    log.Println(s.Shutdown(nil))

    // Wait gorotine print shutdown message
    time.Sleep(time.Second * 5)
    log.Println("done.")
}

運行程序:

go run main.go

而後 ctrl + c 終止該程序,會打印出以下信息:

2017/02/17 11:36:28 interrupt
2017/02/17 11:36:28 <nil>
2017/02/17 11:36:28 http: Server closed
2017/02/17 11:36:28 server shutdown

能夠看到,服務被正確關閉了。

在沒有 Shutdown方法以前,ctrl + c就硬生生的終止了,而後就沒有而後了。

更多內容見官方文檔:

https://golang.org/pkg/net/ht...

相關文章
相關標籤/搜索