diff --git a/gin.go b/gin.go index 02a1062c..a3da5592 100644 --- a/gin.go +++ b/gin.go @@ -353,6 +353,23 @@ func (engine *Engine) Run(addr ...string) (err error) { return } + +// Run attaches the router to a http.Server and starts listening and serving HTTP requests. +// You can use your http.server config like ReadTimeout ... +// It is a shortcut for server.ListenAndServe() +// Note: this method will block the calling goroutine indefinitely unless an error happens. +func (engine *Engine) RunServer(server *http.Server, addr ...string) (err error) { + defer func() { debugPrintError(err) }() + + address := resolveAddress(addr) + debugPrint("Listening and serving HTTP on %s\n", address) + if len(addr) > 0 || server.Addr == "" { + server.Addr = address + } + server.Handler = engine + err = server.ListenAndServe() + return +} func (engine *Engine) prepareTrustedCIDRs() ([]*net.IPNet, error) { if engine.TrustedProxies == nil { return nil, nil diff --git a/gin_integration_test.go b/gin_integration_test.go index 094c46e8..f407e32d 100644 --- a/gin_integration_test.go +++ b/gin_integration_test.go @@ -76,6 +76,7 @@ func TestRunEmpty(t *testing.T) { testRequest(t, "http://localhost:8080/example") } + func TestBadTrustedCIDRsForRun(t *testing.T) { os.Setenv("PORT", "") router := New() @@ -146,20 +147,20 @@ func TestBadTrustedCIDRsForRunTLS(t *testing.T) { func TestRunTLS(t *testing.T) { router := New() + service := &http.Server{} go func() { router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") }) - - assert.NoError(t, router.RunTLS(":8443", "./testdata/certificate/cert.pem", "./testdata/certificate/key.pem")) + assert.NoError(t, router.RunServer(service, ":8090")) }() - // have to wait for the goroutine to start and run the server // otherwise the main thread will complete time.Sleep(5 * time.Millisecond) - assert.Error(t, router.RunTLS(":8443", "./testdata/certificate/cert.pem", "./testdata/certificate/key.pem")) - testRequest(t, "https://localhost:8443/example") + assert.Error(t, router.RunServer(service, ":8090")) + testRequest(t, "http://localhost:8090/example") } + func TestPusher(t *testing.T) { var html = template.Must(template.New("https").Parse(`