From 3e60afc60589fa7d7f6be3f4b1f1d3f06aad55e9 Mon Sep 17 00:00:00 2001 From: Bo-Yi Wu Date: Mon, 7 Apr 2025 15:20:34 +0800 Subject: [PATCH] docs: improve error handling and documentation for EmbedFolder function - Add error handling for the `EmbedFolder` function - Add comments explaining the `embedFileSystem` struct and its `Exists` method - Add imports for `errors` and `strings` packages - Update `TestEmbedFolder` to handle errors from `EmbedFolder` function - Add comments in `embed_folder_test.go` in Chinese for test case explanations Signed-off-by: Bo-Yi Wu --- embed_folder.go | 17 ++++++++++++++--- embed_folder_test.go | 8 +++++++- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/embed_folder.go b/embed_folder.go index c723007..5f455e9 100644 --- a/embed_folder.go +++ b/embed_folder.go @@ -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 } diff --git a/embed_folder_test.go b/embed_folder_test.go index 65ea122..1dc9164 100644 --- a/embed_folder_test.go +++ b/embed_folder_test.go @@ -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 @@ -24,9 +25,14 @@ var embedTests = []struct { {"/static.html", 200, "

Hello Gin Static

", "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, "/")