1package middleware
2
3import (
4	"net/http"
5	"net/http/httptest"
6	"testing"
7
8	"github.com/go-chi/chi/v5"
9)
10
11func TestURLFormat(t *testing.T) {
12	r := chi.NewRouter()
13
14	r.Use(URLFormat)
15
16	r.NotFound(func(w http.ResponseWriter, r *http.Request) {
17		w.WriteHeader(404)
18		w.Write([]byte("nothing here"))
19	})
20
21	r.Route("/samples/articles/samples.{articleID}", func(r chi.Router) {
22		r.Get("/", func(w http.ResponseWriter, r *http.Request) {
23			articleID := chi.URLParam(r, "articleID")
24			w.Write([]byte(articleID))
25		})
26	})
27
28	r.Route("/articles/{articleID}", func(r chi.Router) {
29		r.Get("/", func(w http.ResponseWriter, r *http.Request) {
30			articleID := chi.URLParam(r, "articleID")
31			w.Write([]byte(articleID))
32		})
33	})
34
35	ts := httptest.NewServer(r)
36	defer ts.Close()
37
38	if _, resp := testRequest(t, ts, "GET", "/articles/1.json", nil); resp != "1" {
39		t.Fatalf(resp)
40	}
41	if _, resp := testRequest(t, ts, "GET", "/articles/1.xml", nil); resp != "1" {
42		t.Fatalf(resp)
43	}
44	if _, resp := testRequest(t, ts, "GET", "/samples/articles/samples.1.json", nil); resp != "1" {
45		t.Fatalf(resp)
46	}
47	if _, resp := testRequest(t, ts, "GET", "/samples/articles/samples.1.xml", nil); resp != "1" {
48		t.Fatalf(resp)
49	}
50}
51