跳到內容

伺服器配置

Gin 提供靈活的伺服器配置選項。由於 gin.Engine 實作了 http.Handler 介面,你可以將其與 Go 的標準 net/http.Server 一起使用,直接控制逾時、TLS 和其他設定。

使用自訂 http.Server

預設情況下,router.Run() 啟動一個基本的 HTTP 伺服器。對於正式環境使用,建立你自己的 http.Server 來設定逾時和其他選項:

func main() {
router := gin.Default()
router.GET("/", func(c *gin.Context) {
c.String(200, "ok")
})
s := &http.Server{
Addr: ":8080",
Handler: router,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
s.ListenAndServe()
}

這讓你能完全存取 Go 的伺服器配置,同時保留 Gin 的所有路由和中介軟體功能。

本節內容