没有路线与大猩猩匹配时提供文件?

我使用 Gorilla Mux 作为我的网络服务器。


我定义了一堆路由,但如果没有匹配的路由,我希望它为我的 index.html 文件提供服务。


func (mgr *ApiMgr) InstantiateRestRtr() *mux.Router {

    mgr.pRestRtr = mux.NewRouter().StrictSlash(true)

    mgr.pRestRtr.PathPrefix("/api/").Handler(http.StripPrefix("/api/",

        http.FileServer(http.Dir(mgr.fullPath+"/docsui"))))


    for _, route := range mgr.restRoutes {

        var handler http.Handler

        handler = Logger(route.HandlerFunc, route.Name)

        mgr.pRestRtr.Methods(route.Method)

          .Path(route.Pattern)

          .Name(route.Name)

          .Handler(handler)

    }


    // Here I want to catch any unmatched routes, and serve my '/site/index.html` file. 

    // How can I do this?


    return mgr.pRestRtr

}


牧羊人nacy
浏览 161回答 1
1回答

慕村225694

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 的地方,您可以提供一个新页面
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python