Add Stop function

This commit is contained in:
Nise Void 2019-06-11 16:24:53 +02:00
parent 717c6f65fc
commit 15df08f21b
Signed by: NiseVoid
GPG Key ID: FBA14AC83EA602F3

View File

@ -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 {