예제 #1
0
func TestFull(t *testing.T) {
	mux := NewMux()
	mux.Router.GET("/", httprouter.ContextHandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, "router")
	}))
	mux.SetPreRouteMiddleware(middleware.Chain(middleware.WrapFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request, next httprouter.ContextHandler) {
		fmt.Fprint(w, "premw1")
		next.ServeHTTPContext(ctx, w, r)
		fmt.Fprint(w, "postmw1")
	}),
		middleware.WrapFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request, next httprouter.ContextHandler) {
			fmt.Fprint(w, "premw2")
			next.ServeHTTPContext(ctx, w, r)
			fmt.Fprint(w, "postmw2")
		})))

	resp := httptest.NewRecorder()
	req, err := http.NewRequest("GET", "/", nil)
	if err != nil {
		t.Fatal(err)
	}
	mux.ServeHTTPContext(context.Background(), resp, req)

	if resp.Code != http.StatusOK {
		t.Error("Exected 200 response")
	}

	responseBody, err := resp.Body.ReadString(byte(0))
	if responseBody != "premw1premw2routerpostmw2postmw1" {
		t.Errorf("Wrong order of executing: %s", responseBody)
	}

}
예제 #2
0
func TestMiddlewarePreempt(t *testing.T) {
	mux := NewMux()
	mux.Router.GET("/", httprouter.ContextHandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, "router")
	}))
	mux.SetPreRouteMiddleware(middleware.WrapFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request, next httprouter.ContextHandler) {
		fmt.Fprint(w, "premiddleware")
		return
	}))
	resp := httptest.NewRecorder()
	req, err := http.NewRequest("GET", "/", nil)
	if err != nil {
		t.Fatal(err)
	}
	mux.ServeHTTPContext(context.Background(), resp, req)

	if resp.Code != http.StatusOK {
		t.Error("Exected 200 response")
	}

	responseBody, err := resp.Body.ReadString(byte(0))
	if responseBody != "premiddleware" {
		t.Errorf("Middleware was not preemtive: %s", responseBody)
	}

}