Skip to content

chore(embed): improve error handling for EmbedFolder function #59

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

Merged
merged 1 commit into from
Apr 7, 2025
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions embed_folder.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,41 @@ package static

import (
"embed"
"errors"
"io/fs"
"log/slog"
"net/http"
"strings"
)

// embedFileSystem is a struct that implements the http.FileSystem interface for embedding a file system.
type embedFileSystem struct {
http.FileSystem
}

// Exists method checks if the given file path exists in the embedded file system.
// If the path exists, it returns true; otherwise, it returns false.
func (e embedFileSystem) Exists(prefix string, path string) bool {
if len(prefix) > 1 && strings.HasPrefix(path, prefix) {
path = strings.TrimPrefix(path, prefix)
}

_, err := e.Open(path)
return err == nil
}

func EmbedFolder(fsEmbed embed.FS, targetPath string) ServeFileSystem {
// EmbedFolder function embeds the target folder from the embedded file system into the ServeFileSystem.
// If an error occurs during the embedding process, it returns the error message.
func EmbedFolder(fsEmbed embed.FS, targetPath string) (ServeFileSystem, error) {
fsys, err := fs.Sub(fsEmbed, targetPath)
if err != nil {
slog.Error("Failed to embed folder",
"targetPath", targetPath,
"error", err,
)
return nil
return nil, errors.New("failed to embed folder: " + err.Error())
}
return embedFileSystem{
FileSystem: http.FS(fsys),
}
}, nil
}
8 changes: 7 additions & 1 deletion embed_folder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
//go:embed test/data/server
var server embed.FS

// embedTests 定義了一組測試用例,用於測試嵌入文件系統的行為。
var embedTests = []struct {
targetURL string // input
httpCode int // expected http code
Expand All @@ -24,9 +25,14 @@ var embedTests = []struct {
{"/static.html", 200, "<h1>Hello Gin Static</h1>", "Other file"},
}

// TestEmbedFolder 測試 EmbedFolder 函數的行為,確保其能夠正確嵌入文件夾並提供靜態文件服務。
func TestEmbedFolder(t *testing.T) {
router := gin.New()
router.Use(Serve("/", EmbedFolder(server, "test/data/server")))
fs, err := EmbedFolder(server, "test/data/server")
if err != nil {
t.Fatalf("Failed to embed folder: %v", err)
}
router.Use(Serve("/", fs))
router.NoRoute(func(c *gin.Context) {
fmt.Printf("%s doesn't exists, redirect on /\n", c.Request.URL.Path)
c.Redirect(301, "/")
Expand Down
Loading