mirror of
https://github.com/gin-gonic/gin.git
synced 2025-10-16 21:32:11 +08:00
Add StaticFSFromEmbed Method
This commit is contained in:
parent
f469c1be39
commit
77e922b97c
@ -5,6 +5,8 @@
|
||||
package gin
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"path"
|
||||
"regexp"
|
||||
@ -172,6 +174,33 @@ func (group *RouterGroup) Static(relativePath, root string) IRoutes {
|
||||
return group.StaticFS(relativePath, Dir(root, false))
|
||||
}
|
||||
|
||||
// Define redirectable embed fs interface
|
||||
type fsFunc func(name string) (fs.File, error)
|
||||
|
||||
func (f fsFunc) Open(name string) (fs.File, error) {
|
||||
return f(name)
|
||||
}
|
||||
|
||||
// Redirectable embed files
|
||||
// use :
|
||||
// //go:embed static
|
||||
// var static embed.FS
|
||||
// ......
|
||||
// router.StaticFSFromEmbed("/", "static/", static)
|
||||
func (group *RouterGroup) StaticFSFromEmbed(relativePath, root string, assets embed.FS) IRoutes {
|
||||
fs := http.FS(fsFunc(func(name string) (fs.File, error) {
|
||||
assetPath := path.Join(root, name)
|
||||
// If we can't find the asset, fs can handle the error
|
||||
file, err := assets.Open(assetPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Otherwise assume this is a legitimate request routed correctly
|
||||
return file, err
|
||||
}))
|
||||
return group.StaticFS(relativePath, fs)
|
||||
}
|
||||
|
||||
// StaticFS works just like `Static()` but a custom `http.FileSystem` can be used instead.
|
||||
// Gin by default user: gin.Dir()
|
||||
func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) IRoutes {
|
||||
|
Loading…
x
Reference in New Issue
Block a user