forked from Fuyu/router
Add Stop function
This commit is contained in:
parent
717c6f65fc
commit
15df08f21b
23
router.go
23
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 {
|
||||
|
Loading…
Reference in New Issue
Block a user