MCPcopy
hub / github.com/gorilla/mux / TestMiddlewareOnMultiSubrouter

Function TestMiddlewareOnMultiSubrouter

middleware_test.go:549–622  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

547}
548
549func TestMiddlewareOnMultiSubrouter(t *testing.T) {
550 first := "first"
551 second := "second"
552 notFound := "404 not found"
553
554 router := NewRouter()
555 firstSubRouter := router.PathPrefix("/").Subrouter()
556 secondSubRouter := router.PathPrefix("/").Subrouter()
557
558 router.NotFoundHandler = http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
559 _, err := rw.Write([]byte(notFound))
560 if err != nil {
561 t.Fatalf("Failed writing HTTP response: %v", err)
562 }
563 })
564
565 firstSubRouter.HandleFunc("/first", func(w http.ResponseWriter, r *http.Request) {
566
567 })
568
569 secondSubRouter.HandleFunc("/second", func(w http.ResponseWriter, r *http.Request) {
570
571 })
572
573 firstSubRouter.Use(func(h http.Handler) http.Handler {
574 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
575 _, err := w.Write([]byte(first))
576 if err != nil {
577 t.Fatalf("Failed writing HTTP response: %v", err)
578 }
579 h.ServeHTTP(w, r)
580 })
581 })
582
583 secondSubRouter.Use(func(h http.Handler) http.Handler {
584 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
585 _, err := w.Write([]byte(second))
586 if err != nil {
587 t.Fatalf("Failed writing HTTP response: %v", err)
588 }
589 h.ServeHTTP(w, r)
590 })
591 })
592
593 t.Run("/first uses first middleware", func(t *testing.T) {
594 rw := NewRecorder()
595 req := newRequest("GET", "/first")
596
597 router.ServeHTTP(rw, req)
598 if rw.Body.String() != first {
599 t.Fatalf("Middleware did not run: expected %s middleware to write a response (got %s)", first, rw.Body.String())
600 }
601 })
602
603 t.Run("/second uses second middleware", func(t *testing.T) {
604 rw := NewRecorder()
605 req := newRequest("GET", "/second")
606

Callers

nothing calls this directly

Calls 10

PathPrefixMethod · 0.95
ServeHTTPMethod · 0.95
NewRouterFunction · 0.85
NewRecorderFunction · 0.85
newRequestFunction · 0.85
SubrouterMethod · 0.80
HandlerFuncMethod · 0.80
HandleFuncMethod · 0.80
UseMethod · 0.80
WriteMethod · 0.45

Tested by

no test coverage detected