diff --git a/static.go b/static.go index 6e4050e..2f40174 100644 --- a/static.go +++ b/static.go @@ -1,14 +1,15 @@ package static import ( + "github.com/gin-gonic/gin" "net/http" "os" "path" "strings" - - "github.com/gin-gonic/gin" ) +const INDEX = "index.html" + type ServeFileSystem interface { http.FileSystem Exists(prefix string, path string) bool @@ -35,8 +36,14 @@ func (l *localFileSystem) Exists(prefix string, filepath string) bool { if err != nil { return false } - if !l.indexes && stats.IsDir() { - return false + if stats.IsDir() { + if !l.indexes { + index := path.Join(name, INDEX) + _, err := os.Stat(index) + if err != nil { + return false + } + } } return true } diff --git a/static_test.go b/static_test.go index f66176b..f725004 100644 --- a/static_test.go +++ b/static_test.go @@ -1,15 +1,15 @@ package static import ( + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/assert" "io/ioutil" "net/http" "net/http/httptest" "os" + "path" "path/filepath" "testing" - - "github.com/gin-gonic/gin" - "github.com/stretchr/testify/assert" ) func performRequest(r http.Handler, method, path string) *httptest.ResponseRecorder { @@ -84,3 +84,50 @@ func TestEmptyDirectory(t *testing.T) { assert.Equal(t, w.Code, 200) assert.Equal(t, w.Body.String(), "Gin Web Framework") } + +func TestIndex(t *testing.T) { + // SETUP file + testRoot, _ := os.Getwd() + f, err := os.Create(path.Join(testRoot, "index.html")) + if err != nil { + t.Error(err) + } + defer os.Remove(f.Name()) + f.WriteString("index") + f.Close() + + dir, filename := filepath.Split(f.Name()) + + router := gin.New() + router.Use(ServeRoot("/", dir)) + + w := performRequest(router, "GET", "/"+filename) + assert.Equal(t, w.Code, 301) + + w = performRequest(router, "GET", "/") + assert.Equal(t, w.Code, 200) + assert.Equal(t, w.Body.String(), "index") +} + +func TestListIndex(t *testing.T) { + // SETUP file + testRoot, _ := os.Getwd() + f, err := ioutil.TempFile(testRoot, "") + if err != nil { + t.Error(err) + } + defer os.Remove(f.Name()) + f.WriteString("Gin Web Framework") + f.Close() + + dir, filename := filepath.Split(f.Name()) + router := gin.New() + router.Use(Serve("/", LocalFile(dir, true))) + + w := performRequest(router, "GET", "/"+filename) + assert.Equal(t, w.Code, 200) + assert.Equal(t, w.Body.String(), "Gin Web Framework") + + w = performRequest(router, "GET", "/") + assert.Contains(t, w.Body.String(), `