package sliderule_test import ( "bytes" "context" "io" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" sr "tildegit.org/tjp/sliderule" "tildegit.org/tjp/sliderule/gemini" ) var h1 = sr.HandlerFunc(func(_ context.Context, _ *sr.Request) *sr.Response { return gemini.Success("", &bytes.Buffer{}) }) func mw1(h sr.Handler) sr.Handler { return sr.HandlerFunc(func(ctx context.Context, req *sr.Request) *sr.Response { resp := h.Handle(ctx, req) resp.Body = io.MultiReader(resp.Body, bytes.NewBufferString("\nmiddleware 1")) return resp }) } func mw2(h sr.Handler) sr.Handler { return sr.HandlerFunc(func(ctx context.Context, req *sr.Request) *sr.Response { resp := h.Handle(ctx, req) resp.Body = io.MultiReader(resp.Body, bytes.NewBufferString("\nmiddleware 2")) return resp }) } func TestRouterUse(t *testing.T) { r := &sr.Router{} r.Use(mw1) r.Use(mw2) r.Route("/", h1) request, err := gemini.ParseRequest(bytes.NewBufferString("/\r\n")) require.Nil(t, err) response := r.Handler(context.Background(), request) require.NotNil(t, response) body, err := io.ReadAll(response.Body) require.Nil(t, err) assert.Equal(t, "\nmiddleware 2\nmiddleware 1", string(body)) } func TestRouterMount(t *testing.T) { outer := &sr.Router{} outer.Use(mw2) inner := &sr.Router{} inner.Use(mw1) inner.Route("/bar", h1) outer.Mount("/foo", inner) request, err := gemini.ParseRequest(bytes.NewBufferString("/foo/bar\r\n")) require.Nil(t, err) response := outer.Handler(context.Background(), request) require.NotNil(t, response) body, err := io.ReadAll(response.Body) require.Nil(t, err) assert.Equal(t, "\nmiddleware 1\nmiddleware 2", string(body)) request, err = gemini.ParseRequest(bytes.NewBufferString("/foo\r\n")) require.Nil(t, err) response = outer.Handler(context.Background(), request) require.Nil(t, response) }