跳转到内容

服务器配置

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 的所有路由和中间件能力。

本节内容