From 15df08f21b55abfe63e42cf62ae5bae35ebd3888 Mon Sep 17 00:00:00 2001 From: NiseVoid Date: Tue, 11 Jun 2019 16:24:53 +0200 Subject: [PATCH] Add Stop function --- router.go | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/router.go b/router.go index a878555..dd8cfd7 100644 --- a/router.go +++ b/router.go @@ -1,8 +1,10 @@ package router import ( + "context" "net/http" "reflect" + "time" "github.com/julienschmidt/httprouter" ) @@ -35,6 +37,7 @@ type Router struct { NotFoundHandler Handle MethodNotAllowedHandler Handle ErrorHandler ErrorHandle + server *http.Server } // New returns a new Router @@ -94,7 +97,25 @@ func (r *Router) OPTIONS(path string, handle Handle, middleware ...Middleware) { func (r *Router) Start(addr string) error { httpr := r.getHttpr() - return http.ListenAndServe(addr, httpr) + r.server = &http.Server{Addr: addr, Handler: httpr} + return r.server.ListenAndServe() +} + +// Stop stops the web server +func (r *Router) Stop() error { + if r.server == nil { + return nil + } + + ctx, cancel := context.WithTimeout(context.Background(), time.Duration(time.Second*5)) + defer cancel() + err := r.server.Shutdown(ctx) + if err == context.DeadlineExceeded { + err = r.server.Close() + } + r.server = nil + + return err } func (r *Router) getHttpr() *httprouter.Router {