diff --git a/gin.go b/gin.go index 4dbe9836..db8e1004 100644 --- a/gin.go +++ b/gin.go @@ -295,6 +295,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 http.ListenAndServe(addr, router) +// 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 = address + } + server.Handler = engine + err = server.ListenAndServe() + return +} + // RunTLS attaches the router to a http.Server and starts listening and serving HTTPS (secure) requests. // It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router) // Note: this method will block the calling goroutine indefinitely unless an error happens. diff --git a/gin_integration_test.go b/gin_integration_test.go index 9beec14d..a85d3540 100644 --- a/gin_integration_test.go +++ b/gin_integration_test.go @@ -54,6 +54,22 @@ func TestRunEmpty(t *testing.T) { testRequest(t, "http://localhost:8080/example") } +func TestRunServer(t *testing.T) { + os.Setenv("PORT", "") + router := New() + service := &http.Server{} + go func() { + router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") }) + assert.NoError(t, router.RunServer(service),":8080") + }() + // 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.RunServer(service),":8080") + testRequest(t, "http://localhost:8080/example") +} + func TestRunTLS(t *testing.T) { router := New() go func() {