feat(gin,run): add expose out http.Server can use Server config

This commit is contained in:
yangqiuhua 2019-05-16 10:36:35 +08:00
parent 5a7e3095b2
commit 8fd5324a5f
2 changed files with 33 additions and 0 deletions

17
gin.go
View File

@ -295,6 +295,23 @@ func (engine *Engine) Run(addr ...string) (err error) {
return 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. // 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) // It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router)
// Note: this method will block the calling goroutine indefinitely unless an error happens. // Note: this method will block the calling goroutine indefinitely unless an error happens.

View File

@ -54,6 +54,22 @@ func TestRunEmpty(t *testing.T) {
testRequest(t, "http://localhost:8080/example") 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) { func TestRunTLS(t *testing.T) {
router := New() router := New()
go func() { go func() {