Last active
August 29, 2015 14:15
-
-
Save talbright/b63761338d14803ce371 to your computer and use it in GitHub Desktop.
Better martini error handler that supports 404 and 405 scenerios
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"github.com/talbright/martini" | |
"net/http" | |
"strings" | |
"fmt" | |
) | |
func generic() string { | |
return "Generic Handler" | |
} | |
func NotFound(res http.ResponseWriter,req *http.Request,routes martini.Routes) { | |
availMethods := routes.MethodsFor(req.URL.Path) | |
if len(availMethods)>0 { | |
res.Header().Set("Allow", strings.Join(availMethods,",")) | |
http.Error(res, "405 method not allowed", http.StatusMethodNotAllowed) | |
}else{ | |
http.Error(res, "404 page not found", http.StatusNotFound) | |
} | |
} | |
func main() { | |
m := martini.Classic() | |
// curl -i -XPUT http://localhost:3000 | |
// curl -i -XGET http://localhost:3000 | |
m.Get("/", generic) | |
m.NotFound(NotFound) | |
m.Group("/worlds", func(r martini.Router) { | |
// curl -i -XPUT http://localhost:3000/worlds/new | |
// curl -i -XGET http://localhost:3000/worlds/new | |
r.Post("/new", generic) | |
r.Put("/new", generic) | |
r.Delete("/new", generic) | |
}) | |
m.Run() | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment