logo
Public
0
0
WeChat Login
docs: 更新文档结构和内容

静态文件服务示例

本目录当前提供的是静态文件服务用法说明,而不是一个可直接 go run 的独立示例程序。

如果你想看可执行示例,建议从以下位置组合验证:

  • examples/basic/main.go
  • docs/usage.md
  • pkg/static/zipfs.go

能力概览

github.com/darkit/gin 当前支持以下静态资源能力:

  1. 本地目录:Static / StaticFS
  2. 单文件:StaticFile
  3. 嵌入式资源:EmbedFS / EmbedFile
  4. Zip 文件系统:pkg/static 下的 RegisterZipFS / RegisterZipFile

1. 本地文件系统

服务整个目录

package main import gin "github.com/darkit/gin" func main() { e := gin.New() r := e.Router() r.Static("/assets", "./public") _ = e.Run(":8080") }

访问示例:

  • http://localhost:8080/assets/style.css./public/style.css
  • http://localhost:8080/assets/js/app.js./public/js/app.js

服务单个文件

r.StaticFile("/favicon.ico", "./assets/favicon.ico")

使用 http.FileSystem

import "net/http" r.StaticFS("/files", http.Dir("./uploads"))

2. 嵌入式文件系统

package main import ( "embed" gin "github.com/darkit/gin" ) //go:embed dist/* var embedFS embed.FS func main() { e := gin.New() r := e.Router() r.EmbedFS("/static", embedFS, "dist") r.EmbedFile("/favicon.ico", embedFS, "dist/favicon.ico") _ = e.Run(":8080") }

3. Zip 文件系统

Zip 相关能力位于 github.com/darkit/gin/pkg/static

package main import ( gin "github.com/darkit/gin" "github.com/darkit/gin/pkg/static" ) func main() { e := gin.New() r := e.Router() zfs, err := static.NewZipFileSystem(static.ZipFSConfig{ ZipPath: "app.zip", URLPrefix: "/app", }) if err != nil { panic(err) } static.RegisterZipFS(r.RouterGroup, "/app", zfs) _ = e.Run(":8080") }

单文件 Zip 注册:

zf, err := static.NewZipFile("app.zip", "index.html", nil) if err != nil { panic(err) } static.RegisterZipFile(r.RouterGroup, "/index", zf)

密码保护的 Zip

zfs, err := static.NewZipFileSystem(static.ZipFSConfig{ ZipPath: "protected.zip", URLPrefix: "/secure", Password: "mypassword", }) if err != nil { panic(err) } static.RegisterZipFS(r.RouterGroup, "/secure", zfs)

Zip 文件热更新

zfs, err := static.NewZipFileSystem(static.ZipFSConfig{ ZipPath: "app.zip", URLPrefix: "/app", HotReload: true, CheckInterval: 3 * time.Second, }) if err != nil { panic(err) } static.RegisterZipFS(r.RouterGroup, "/app", zfs) zfs.StartHotReload() defer zfs.Stop()

也可使用辅助 option:

cfg := static.NewZipFSConfig( "app.zip", "/app", static.WithPassword("mypassword"), static.WithHotReload(3*time.Second), ) zfs, err := static.NewZipFileSystem(cfg)

4. Engine 层面的静态路由

Engine 也直接暴露静态相关注册方法:

e.Static("/assets", "./public") e.StaticFile("/favicon.ico", "./favicon.ico") e.StaticFS("/files", http.Dir("./uploads"))

最佳实践

  1. 生产环境优先考虑 EmbedFS 或 CDN
  2. 开发环境可直接使用本地目录映射
  3. 大型资源包可考虑 Zip 文件系统
  4. 如需保护内容,可启用 Zip 密码能力
  5. 开发阶段如需替换 Zip 包,可启用热更新
  6. 用户上传资源与前端静态资源建议分离路径

进一步阅读

  • docs/usage.md
  • pkg/static/zipfs.go
  • README.md