想要優雅地重啟或停止你的Web服務器,使用下面的方法
我們可以使用[fvbock/endless](https://github.com/fvbock/endless)來替換默認的`ListenAndServe`,有關詳細信息,請參閱問題[#296](https://github.com/gin-gonic/gin/issues/296)
```
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)方法進行優雅關閉,查看[例子](https://github.com/gin-gonic/gin/tree/master/examples/graceful-shutdown)
```
// +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() {
// service connections
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}()
// Wait for interrupt signal to gracefully shutdown the server with
// a timeout of 5 seconds.
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")
}
```
- 簡介
- 安裝
- 快速入門
- 代碼示例
- 使用 GET, POST, PUT, PATCH, DELETE, OPTIONS
- 獲取路徑中的參數
- 獲取Get參數
- 獲取Post參數
- Get + Post 混合
- 上傳文件
- 路由分組
- 無中間件啟動
- 使用中間件
- 寫日志文件
- 自定義日志格式
- 模型綁定和驗證
- 自定義驗證器
- 只綁定Get參數
- 綁定Get參數或者Post參數
- 綁定uri
- 綁定HTML復選框
- 綁定Post參數
- XML、JSON、YAML和ProtoBuf 渲染(輸出格式)
- 設置靜態文件路徑
- 返回第三方獲取的數據
- HTML渲染
- 多個模板文件
- 重定向
- 自定義中間件
- 使用BasicAuth()(驗證)中間件
- 中間件中使用Goroutines
- 自定義HTTP配置
- 支持Let's Encrypt證書
- Gin運行多個服務
- 優雅重啟或停止
- 構建包含模板的二進制文件
- 使用自定義結構綁定表單數據
- 將請求體綁定到不同的結構體中
- HTTP/2 服務器推送
- 自定義路由日志的格式
- 設置并獲取cookie
- 測試
- 用戶