Page MenuHomePhabricator
Paste P17477

Overriding NotFound & MethodNotAllowed errors
ActivePublic

Authored by Eevans on Oct 13 2021, 8:12 PM.
Tags
None
Referenced Files
F34687581: Overriding NotFound & MethodNotAllowed errors
Oct 13 2021, 8:14 PM
F34687580: Overriding NotFound & MethodNotAllowed errors
Oct 13 2021, 8:12 PM
Subscribers
None
package main
import (
"fmt"
"log"
"net/http"
"github.com/julienschmidt/httprouter"
"schneider.vip/problem"
)
func problemHandler(status int) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Content-Type-Options", "nosniff")
problem.Of(status).WriteTo(w)
})
}
func main() {
router := httprouter.New()
// Assign http.Handlers that return a JSON-encoded problem object
router.NotFound = problemHandler(http.StatusNotFound)
router.MethodNotAllowed = problemHandler(http.StatusMethodNotAllowed)
router.GET("/hello/:name", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
})
log.Fatal(http.ListenAndServe(":8080", router))
}

Event Timeline

Eevans edited the content of this paste. (Show Details)