Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

static: trim slash before opening file #170

Merged
merged 1 commit into from
Aug 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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