Skip to content

Commit

Permalink
static: trim slash before opening file (#170)
Browse files Browse the repository at this point in the history
  • Loading branch information
wuhan005 committed Aug 7, 2023
1 parent 977c36e commit b567fe0
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 7 deletions.
3 changes: 3 additions & 0 deletions static.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,9 @@ func Static(opts ...StaticOptions) Handler {
}
}

// The go embed file system returns an error when the path ends with a slash.
file = strings.TrimRight(file, "/")

f, err := opt.FileSystem.Open(file)
if err != nil {
return
Expand Down
33 changes: 26 additions & 7 deletions static_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package flamego

import (
"bytes"
"embed"
"net/http"
"net/http/httptest"
"testing"
Expand All @@ -15,6 +16,9 @@ import (
"github.com/stretchr/testify/assert"
)

//go:embed internal
var embedFS embed.FS

func TestStatic(t *testing.T) {
f := NewWithLogger(&bytes.Buffer{})
f.Use(Static(
Expand Down Expand Up @@ -119,30 +123,45 @@ func TestStatic_Options(t *testing.T) {

t.Run("index", func(t *testing.T) {
tests := []struct {
uri string
index string
wantStatusCode int
}{
{
uri: "/",
index: ".editorconfig",
wantStatusCode: http.StatusOK,
},
{
uri: "/",
index: "index.html",
wantStatusCode: http.StatusNotFound,
},
{
uri: "/embed/internal/route/",
index: "README.md",
wantStatusCode: http.StatusOK,
},
}
for _, test := range tests {
t.Run(test.index, func(t *testing.T) {
f := NewWithLogger(&bytes.Buffer{})
f.Use(Static(
StaticOptions{
Directory: ".",
Index: test.index,
},
))
f.Use(
Static(
StaticOptions{
Directory: ".",
Index: test.index,
},
),
Static(StaticOptions{
FileSystem: http.FS(embedFS),
Prefix: "/embed",
Index: test.index,
}),
)

resp := httptest.NewRecorder()
req, err := http.NewRequest(http.MethodHead, "/", http.NoBody)
req, err := http.NewRequest(http.MethodHead, test.uri, http.NoBody)
assert.Nil(t, err)

f.ServeHTTP(resp, req)
Expand Down

0 comments on commit b567fe0

Please sign in to comment.