你想優雅地重啟或停止 web 服務器嗎?有一些方法可以做到這一點。
我們可以使用 [fvbock/endless](https://github.com/fvbock/endless) 來替換默認的 `ListenAndServe`。更多詳細信息,請參閱 issue [#296](https://github.com/gin-gonic/gin/issues/296)。
```go
router := gin.Default()
router.GET("/", handler)
// [...]
endless.ListenAndServe(":4242", router)
```
替代方案:
* [manners](https://github.com/braintree/manners):可以優雅關機的 Go Http 服務器。
* [graceful](https://github.com/tylerb/graceful):Graceful 是一個 Go 擴展包,可以優雅地關閉 http.Handler 服務器。
* [grace](https://github.com/facebookgo/grace):Go 服務器平滑重啟和零停機時間部署。
如果你使用的是 Go 1.8,可以不需要這些庫!考慮使用 http.Server 內置的 [Shutdown()](https://golang.org/pkg/net/http/#Server.Shutdown) 方法優雅地關機. 請參閱 gin 完整的 [graceful-shutdown](https://github.com/gin-gonic/examples/tree/master/graceful-shutdown) 示例。
```go
// +build go1.8
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"time"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.GET("/", func(c *gin.Context) {
time.Sleep(5 * time.Second)
c.String(http.StatusOK, "Welcome Gin Server")
})
srv := &http.Server{
Addr: ":8080",
Handler: router,
}
go func() {
// 服務連接
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}()
// 等待中斷信號以優雅地關閉服務器(設置 5 秒的超時時間)
quit := make(chan os.Signal)
signal.Notify(quit, os.Interrupt)
<-quit
log.Println("Shutdown Server ...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatal("Server Shutdown:", err)
}
log.Println("Server exiting")
}
```
- 介紹
- 快速入門
- 基準測試
- 特性
- Jsoniter
- 示例
- AsciiJSON
- HTML 渲染
- HTTP2 server 推送
- JSONP
- Multipart/Urlencoded 綁定
- Multipart/Urlencoded 表單
- PureJSON
- Query 和 post form
- SecureJSON
- XML/JSON/YAML/ProtoBuf 渲染
- 上傳文件
- 單文件
- 多文件
- 不使用默認的中間件
- 從 reader 讀取數據
- 優雅地重啟或停止
- 使用 BasicAuth 中間件
- 使用 HTTP 方法
- 使用中間件
- 只綁定 url 查詢字符串
- 在中間件中使用 Goroutine
- 多模板
- 如何記錄日志
- 定義路由日志的格式
- 將 request body 綁定到不同的結構體中
- 支持 Let's Encrypt
- 映射查詢字符串或表單參數
- 查詢字符串參數
- 模型綁定和驗證
- 綁定 HTML 復選框
- 綁定 Uri
- 綁定查詢字符串或表單數據
- 綁定表單數據至自定義結構體
- 自定義 HTTP 配置
- 自定義中間件
- 自定義驗證器
- 設置和獲取 Cookie
- 路由參數
- 路由組
- 運行多個服務
- 重定向
- 靜態文件服務
- 靜態資源嵌入
- 測試
- 用戶
- FAQ