1package route 2 3import ( 4 "net/http" 5 "net/http/httptest" 6 "testing" 7) 8 9func TestRedirect(t *testing.T) { 10 router := New().WithPrefix("/test/prefix") 11 w := httptest.NewRecorder() 12 r, err := http.NewRequest("GET", "http://localhost:9090/foo", nil) 13 if err != nil { 14 t.Fatalf("Error building test request: %s", err) 15 } 16 17 router.Redirect(w, r, "/some/endpoint", http.StatusFound) 18 if w.Code != http.StatusFound { 19 t.Fatalf("Unexpected redirect status code: got %d, want %d", w.Code, http.StatusFound) 20 } 21 22 want := "/test/prefix/some/endpoint" 23 got := w.Header()["Location"][0] 24 if want != got { 25 t.Fatalf("Unexpected redirect location: got %s, want %s", got, want) 26 } 27} 28 29func TestContext(t *testing.T) { 30 router := New() 31 router.Get("/test/:foo/", func(w http.ResponseWriter, r *http.Request) { 32 want := "bar" 33 got := Param(r.Context(), "foo") 34 if want != got { 35 t.Fatalf("Unexpected context value: want %q, got %q", want, got) 36 } 37 }) 38 39 r, err := http.NewRequest("GET", "http://localhost:9090/test/bar/", nil) 40 if err != nil { 41 t.Fatalf("Error building test request: %s", err) 42 } 43 router.ServeHTTP(nil, r) 44} 45 46func TestInstrumentation(t *testing.T) { 47 var got string 48 cases := []struct { 49 router *Router 50 want string 51 }{ 52 { 53 router: New(), 54 want: "", 55 }, { 56 router: New().WithInstrumentation(func(handlerName string, handler http.HandlerFunc) http.HandlerFunc { 57 got = handlerName 58 return handler 59 }), 60 want: "/foo", 61 }, 62 } 63 64 for _, c := range cases { 65 c.router.Get("/foo", func(w http.ResponseWriter, r *http.Request) {}) 66 67 r, err := http.NewRequest("GET", "http://localhost:9090/foo", nil) 68 if err != nil { 69 t.Fatalf("Error building test request: %s", err) 70 } 71 c.router.ServeHTTP(nil, r) 72 if c.want != got { 73 t.Fatalf("Unexpected value: want %q, got %q", c.want, got) 74 } 75 } 76} 77