Esempio n. 1
0
func main() {
	app := mux.NewRouter()
	app.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})

	app.Get("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "hello")
	})

	notFound := middleware.NotFound(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "custom 404 page")
	})

	fileServer := middleware.FileServer(http.Dir("."))
	logger := middleware.Logger

	log.Println("listening on port 8080")
	log.Fatal(http.ListenAndServe(":8080", alice.New(logger, notFound, fileServer).Then(app)))
}
Esempio n. 2
0
func TestNotFound(t *testing.T) {
	notFound := middleware.NotFound(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "custom 404")
	})

	Describe("when an earlier handler writes a non-404 response", func() {
		mainHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			fmt.Fprintf(w, "hello")
		})

		w := httptest.NewRecorder()
		r, err := http.NewRequest("GET", "/", nil)
		if err != nil {
			t.Error(err)
			return
		}

		notFound(mainHandler).ServeHTTP(w, r)

		It("should return the written status code", func() {
			assert.Equal(t, 200, w.Code)
		})

		It("should return the written body", func() {
			assert.Equal(t, "hello", w.Body.String())
		})
	})

	Describe("when an earlier handler writes a 404", func() {
		mainHandler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
			w.WriteHeader(404)
		})

		w := httptest.NewRecorder()
		r, err := http.NewRequest("GET", "/", nil)
		if err != nil {
			t.Error(err)
			return
		}

		notFound(mainHandler).ServeHTTP(w, r)

		It("should return the custom 404 response", func() {
			assert.Equal(t, "custom 404", w.Body.String())
		})
	})

	Describe("when nothing has been written", func() {
		emptyHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})

		w := httptest.NewRecorder()
		r, err := http.NewRequest("GET", "/", nil)
		if err != nil {
			t.Error(err)
			return
		}

		notFound(emptyHandler).ServeHTTP(w, r)

		It("should return the custom 404 response", func() {
			assert.Equal(t, "custom 404", w.Body.String())
		})
	})
}