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