From 94b4285289af2569990b5f2608feeab40d9cf500 Mon Sep 17 00:00:00 2001 From: Vincent Vanackere Date: Tue, 7 Jan 2014 08:57:27 +0100 Subject: [PATCH] Static : add support for HEAD requests (also avoid useless filesystem call for non HEAD/GET requests) --- static.go | 5 ++++- static_test.go | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/static.go b/static.go index d36d9e9..e169fb4 100644 --- a/static.go +++ b/static.go @@ -11,9 +11,12 @@ import ( func Static(directory string) Handler { dir := http.Dir(directory) return func(res http.ResponseWriter, req *http.Request, log *log.Logger) { + if req.Method != "GET" && req.Method != "HEAD" { + return + } file := req.URL.Path f, err := dir.Open(file) - if err != nil || req.Method != "GET" { + if err != nil { // discard the error? return } diff --git a/static_test.go b/static_test.go index 33e862d..243a558 100644 --- a/static_test.go +++ b/static_test.go @@ -22,6 +22,22 @@ func Test_Static(t *testing.T) { expect(t, response.Code, http.StatusOK) } +func Test_Static_Head(t *testing.T) { + response := httptest.NewRecorder() + + m := New() + + m.Use(Static(".")) + + req, err := http.NewRequest("HEAD", "http://localhost:3000/martini.go", nil) + if err != nil { + t.Error(err) + } + + m.ServeHTTP(response, req) + expect(t, response.Code, http.StatusOK) +} + func Test_Static_As_Post(t *testing.T) { response := httptest.NewRecorder()