package httpr_test import ( "net/http" "net/http/httptest" "os" "strings" "testing" "git.arav.su/Arav/httpr" ) func Test(t *testing.T) { r := httpr.New() err := r.Handler(http.MethodGet, "/", func(w http.ResponseWriter, r *http.Request) {}) if err != nil { t.Fatal(err) } err = r.Handler(http.MethodGet, "/", func(w http.ResponseWriter, r *http.Request) {}) if err == nil { t.Fatal("path redefinition wasn't catched") } err = r.Handler(http.MethodGet, "/a/b", func(w http.ResponseWriter, r *http.Request) {}) if err != nil { t.Fatal(err) } err = r.Handler(http.MethodGet, "/:a/:b", func(w http.ResponseWriter, r *http.Request) {}) if err != nil { t.Fatal(err) } err = r.Handler(http.MethodGet, "/:a/:lol", func(w http.ResponseWriter, r *http.Request) {}) if err == nil { t.Fatal("here is a different last param name is supplied, should be catched") } err = r.ServeStatic("/assets/*filepath", http.FS(os.DirFS("."))) if err != nil { t.Fatal(err) } err = r.ServeStatic("/assets/*filepath/*filepath", nil) if err == nil { t.Fatal("multiple catch-all params wasn't catched") } } func TestPaths(t *testing.T) { found := false r := httpr.New() err := r.Handler(http.MethodGet, "/:lel", func(w http.ResponseWriter, r *http.Request) { found = true }) if err != nil { t.Fatal(err) } r.NotFoundHandler = func(w http.ResponseWriter, r *http.Request) { found = false } w := httptest.NewRecorder() p := "/xmpp://me@arav.su" req := httptest.NewRequest(http.MethodGet, p, strings.NewReader("")) r.ServeHTTP(w, req) if found { t.Error("Path", p, "should return 404") } p = "/lel" req = httptest.NewRequest(http.MethodGet, p, strings.NewReader("")) r.ServeHTTP(w, req) if !found { t.Error("Path", p, "should return 200") } p = "/lel/lol" req = httptest.NewRequest(http.MethodGet, p, strings.NewReader("")) r.ServeHTTP(w, req) if found { t.Error("Path", p, "should return 404") } } func TestSubPaths(t *testing.T) { found := true r := httpr.New() s := r.Sub("/api/v1") err := s.Handler(http.MethodGet, "/", func(w http.ResponseWriter, r *http.Request) { found = true }) if err != nil { t.Fatal(err) } err = s.Handler(http.MethodGet, "/test", func(w http.ResponseWriter, r *http.Request) { found = true }) if err != nil { t.Fatal(err) } r.NotFoundHandler = func(w http.ResponseWriter, r *http.Request) { found = false } w := httptest.NewRecorder() p := "/api/v1/" req := httptest.NewRequest(http.MethodGet, p, strings.NewReader("")) r.ServeHTTP(w, req) if !found { t.Error("Path", p, "should return 200") } p = "/api/v1/test" req = httptest.NewRequest(http.MethodGet, p, strings.NewReader("")) r.ServeHTTP(w, req) if !found { t.Error("Path", p, "should return 200") } p = "/api/v1/nonexistent" req = httptest.NewRequest(http.MethodGet, p, strings.NewReader("")) r.ServeHTTP(w, req) if found { t.Error(found, "Path", p, "should return 404") } }