亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

沒有路線與大猩猩匹配時提供文件?

沒有路線與大猩猩匹配時提供文件?

牧羊人nacy 2022-03-07 15:49:08
我使用 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}
查看完整描述

1 回答

?
慕村225694

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 的地方,您可以提供一個新頁面


查看完整回答
反對 回復 2022-03-07
  • 1 回答
  • 0 關注
  • 180 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號