Skip to content

Instantly share code, notes, and snippets.

@talbright
Last active August 29, 2015 14:15
Show Gist options
  • Save talbright/b63761338d14803ce371 to your computer and use it in GitHub Desktop.
Save talbright/b63761338d14803ce371 to your computer and use it in GitHub Desktop.
Better martini error handler that supports 404 and 405 scenerios
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