fix index.html issue (#8)

/index.html will automatic redirect to /
refer:https://github.com/golang/go/blob/master/src/net/http/fs.go#L541
This commit is contained in:
yinheli 2018-08-27 10:49:05 +08:00 committed by Bo-Yi Wu
parent 1242926197
commit 1d5ab15f82
2 changed files with 61 additions and 7 deletions

View File

@ -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
}

View File

@ -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(), `<a href="`+filename)
}