From e7c7ec55acd7a0844288dab45def57be63d0d81d Mon Sep 17 00:00:00 2001 From: Scott Thompson Date: Mon, 18 Aug 2014 00:45:43 +0100 Subject: [PATCH] Added a NotFound() method so a handler can be specified in the event that no routes match allowing a custom 404 page to be produced --- README.md | 4 ++++ routes.go | 15 ++++++++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 1e88ad0..db47c2f 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,10 @@ You can specify custom regular expressions for routes: mux.Get("/files/:param(.+)", handler) +You can specify a custom 404 not found route: + + mux.NotFound(handler) + You can also create routes for static files: pwd, _ := os.Getwd() diff --git a/routes.go b/routes.go index 6870373..92d8d39 100644 --- a/routes.go +++ b/routes.go @@ -38,15 +38,22 @@ type route struct { handler http.HandlerFunc } +type notFoundHandler func(http.ResponseWriter, *http.Request) + type RouteMux struct { routes []*route filters []http.HandlerFunc + notFoundHandler notFoundHandler } func New() *RouteMux { return &RouteMux{} } +func (m *RouteMux) NotFound(handler notFoundHandler) { + m.notFoundHandler = handler +} + // Get adds a new Route for GET requests. func (m *RouteMux) Get(pattern string, handler http.HandlerFunc) { m.AddRoute(GET, pattern, handler) @@ -206,7 +213,13 @@ func (m *RouteMux) ServeHTTP(rw http.ResponseWriter, r *http.Request) { //if no matches to url, throw a not found exception if w.started == false { - http.NotFound(w, r) + + if (m.notFoundHandler != nil) { + m.notFoundHandler(w, r) + } else { + http.NotFound(w, r) + } + } }