2017-06-21 152 views
0

我想只在一些路由上添加一箇中間件。我寫了這個代碼:Subroutes中間件與大猩猩MUX和Negroni

func main() { 
    router := mux.NewRouter().StrictSlash(false) 

    admin_subrouter := router.PathPrefix("/admin").Subrouter() 

    //handlers.CombinedLoggingHandler comes from gorilla/handlers 
    router.PathPrefix("/admin").Handler(negroni.New(
    negroni.Wrap(handlers.CombinedLoggingHandler(os.Stdout, admin_subrouter)), 
)) 

    admin_subrouter.HandleFunc("/articles/new", articles_new).Methods("GET") 
    admin_subrouter.HandleFunc("/articles", articles_index).Methods("GET") 
    admin_subrouter.HandleFunc("/articles", articles_create).Methods("POST") 

    n := negroni.New() 
    n.UseHandler(router) 
    http.ListenAndServe(":3000", n) 

}

我希望看到的請求日誌只能用於前綴/管理路徑。當我做「GET/admin」時,我確實看到了一條日誌行,但當我做「GET/admin/articles/new」時沒有看到。我試圖通過蠻力其他組合,但我無法得到它。我的代碼有什麼問題?

我看到了其他方式,比如在每個路由定義上包裝HandlerFunc,但是我想爲前綴或子路由器執行一次。

我在那裏使用的日誌記錄中間件用於測試,也許一個Auth中間件更有意義,但我只是想讓它工作。

謝謝!

回答

1

問題是您創建子路線/admin的方式。完整的參考代碼是https://play.golang.org/p/zb_79oHJed

// Admin 
adminBase := mux.NewRouter() 
router.PathPrefix("/admin").Handler(negroni.New(
    // This logger only applicable to /admin routes 
    negroni.HandlerFunc(justTestLogger), 
    // add your handlers here which is only appilcable to `/admin` routes 
    negroni.Wrap(adminBase), 
)) 

adminRoutes := adminBase.PathPrefix("/admin").Subrouter() 
adminRoutes.HandleFunc("/articles/new", articleNewHandler).Methods("GET") 

現在,訪問這些網址。您將只能看到/admin子路線的日誌。

+0

工作,謝謝。我想使用Gorilla包處理程序中提供的中間件。 –

+0

然後,我能夠用大猩猩做處理。 'router.PathPrefix( 「/ admin」 的)處理程序(negroni.New( \t negroni.Wrap(handlers.CombinedLoggingHandler(os.Stdout,adminBase)), \t)) ' –

+0

是的,你可以使用它,只是爲了演示子路由器的定義,我沒有在例子中使用它。對於那個很抱歉。 – jeevatkm