package gus_test import ( "bytes" "context" "io" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "tildegit.org/tjp/gus" "tildegit.org/tjp/gus/gemini" ) var h1 = gus.HandlerFunc(func(_ context.Context, _ *gus.Request) *gus.Response { return gemini.Success("", &bytes.Buffer{}) }) func mw1(h gus.Handler) gus.Handler { return gus.HandlerFunc(func(ctx context.Context, req *gus.Request) *gus.Response { resp := h.Handle(ctx, req) resp.Body = io.MultiReader(resp.Body, bytes.NewBufferString("\nmiddleware 1")) return resp }) } func mw2(h gus.Handler) gus.Handler { return gus.HandlerFunc(func(ctx context.Context, req *gus.Request) *gus.Response { resp := h.Handle(ctx, req) resp.Body = io.MultiReader(resp.Body, bytes.NewBufferString("\nmiddleware 2")) return resp }) } func TestRouterUse(t *testing.T) { r := &gus.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 := &gus.Router{} outer.Use(mw2) inner := &gus.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) }