1 回答
TA贡献1880条经验 获得超4个赞
func NewRouter() *mux.Router {
router := mux.NewRouter().StrictSlash(true)
routes := client.GetRoutes()
for _, route := range routes {
var handler http.Handler
handler = route.HandlerFunc
handler = context.ClearHandler(handler)
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(handler)
}
r := OGRouter{router: router}
router = r.router
router.NotFoundHandler = http.HandlerFunc(r.NotFoundHandler)
return router
}
/* Handled mux router drawback of giving 404 in every case i.e if either URI or METHOD
* is not matched mux router will give 404. So, this case is handled her, if Method will
* not match we will through 405
*/
func (router *OGRouter) NotFoundHandler(rw http.ResponseWriter, req *http.Request) {
r := *router.router
route := r.Get(req.RequestURI)
if route != nil {
if req.RequestURI == route.GetName() {
routeMatch := mux.RouteMatch{Route: route}
if !route.Match(req, &routeMatch) {
rw.WriteHeader(http.StatusMethodNotAllowed)
}
} else {
rw.WriteHeader(http.StatusNotFound)
}
} else {
rw.WriteHeader(http.StatusNotFound)
}
}
type OGRouter struct {
router *mux.Router
}
在您获得 404 的地方,您可以提供一个新页面
添加回答
举报