summaryrefslogtreecommitdiff
path: root/router_test.go
diff options
context:
space:
mode:
Diffstat (limited to 'router_test.go')
-rw-r--r--router_test.go80
1 files changed, 80 insertions, 0 deletions
diff --git a/router_test.go b/router_test.go
new file mode 100644
index 0000000..6f9c915
--- /dev/null
+++ b/router_test.go
@@ -0,0 +1,80 @@
+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"
+)
+
+func h1(_ context.Context, _ *gus.Request) *gus.Response {
+ return gemini.Success("", &bytes.Buffer{})
+}
+
+func mw1(h gus.Handler) gus.Handler {
+ return func(ctx context.Context, req *gus.Request) *gus.Response {
+ resp := h(ctx, req)
+ resp.Body = io.MultiReader(resp.Body, bytes.NewBufferString("\nmiddleware 1"))
+ return resp
+ }
+}
+
+func mw2(h gus.Handler) gus.Handler {
+ return func(ctx context.Context, req *gus.Request) *gus.Response {
+ resp := h(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)
+}