用途:在 Relic 应用中提供静态文件与目录访问,适用于托管资源、图片、CSS、JS、favicon 等,并可配置 HTTP 缓存。
主要能力:StaticHandler 提供文件服务,自动检测 MIME 类型、生成缓存头,并内置安全防护。安全保护自动生效:路径穿越防护,阻止 ../ 逃逸所服务目录;隐藏文件拦截,阻止以 . 开头的文件(如 .env、.git);符号链接在允许目录内安全解析。
使用方式:服务目录时使用尾通配模式(/),让处理器知道要提供哪个文件: app.anyOf( {Method.get, Method.head}, '/static/', StaticHandler.directory( Directory('public'), cacheControl: (req, fileInfo) => CacheControlHeader(maxAge: 86400), ).asHandler, ); // public/style.css → http://localhost:8080/static/style.css
服务单个文件: app.get( '/logo.svg', StaticHandler.file( File('assets/logo.svg'), cacheControl: (req, fileInfo) => CacheControlHeader(maxAge: 3600), ).asHandler, );
缓存控制策略:短期用于频繁更新内容,可设 maxAge: 3600、publicCache: true 允许 CDN/代理缓存;长期不可变用于带版本资源,可设 maxAge: 31536000、publicCache: true、immutable: true,浏览器不再重新校验。
缓存失效(cache busting):依据文件内容哈希生成唯一 URL,内容变化则哈希变化,强制浏览器获取新版本。 final buster = CacheBustingConfig( mountPrefix: '/static', fileSystemRoot: Directory('public'), ); // 生成带缓存失效的 URL(例如 /static/hello@6cb65f8d.txt) app.get('/', respondWith((req) async { final cssUrl = await buster.assetPath('/static/style.css'); final html = '<link rel="stylesheet" href="$cssUrl">'; return Response.ok(body: Body.fromString(html, mimeType: MimeType.html)); })); // 配合激进缓存(URL 随内容变化,因此安全) app.anyOf( {Method.get, Method.head}, '/static/**', StaticHandler.directory( Directory('public'), cacheControl: (req, fileInfo) => CacheControlHeader( maxAge: 31536000, publicCache: true, immutable: true, ), cacheBustingConfig: buster, ).asHandler, );
限制:资料未提供适用的 Relic 版本、性能数据、支持的 MIME 类型范围及具体部署平台信息。