# 动态资产 :::info This does not work with vite v5.0.0+ and wails v2 due to changes in vite. Changes are planned in v3 to support similar functionality under vite v5.0.0+. If you need this feature, stay with vite v4.0.0+. See [issue 3240](https://github.com/wailsapp/wails/issues/3240) for details ::: 如果你想为你的前端动态加载或生成资产,你可以使用 [AssetsHandler 选项](../reference/options#资产处理程序) 来实现。 AssetsHandler 是一个通用的 `http.Handler`,对于资产服务器上的任何非 GET 请求以及由于找不到文件而无法从捆绑资产提供服务的 GET 请求,都会调用它。 通过安装自定义 AssetsHandler,您可以使用自定义资产服务器提供您自己的资产。 ## 示例 在我们的示例项目中,我们将创建一个简单的资产处理程序,它将从磁盘加载文件: ```go title=main.go {17-36,49} package main import ( "embed" "fmt" "github.com/wailsapp/wails/v2" "github.com/wailsapp/wails/v2/pkg/options" "github.com/wailsapp/wails/v2/pkg/options/assetserver" "net/http" "os" "strings" ) //go:embed all:frontend/dist var assets embed.FS type FileLoader struct { http.Handler } func NewFileLoader() *FileLoader { return &FileLoader{} } func (h *FileLoader) ServeHTTP(res http.ResponseWriter, req *http.Request) { var err error requestedFilename := strings.TrimPrefix(req.URL.Path, "/") println("Requesting file:", requestedFilename) fileData, err := os.ReadFile(requestedFilename) if err != nil { res.WriteHeader(http.StatusBadRequest) res.Write([]byte(fmt.Sprintf("Could not load file %s", requestedFilename))) } res.Write(fileData) } func main() { // Create an instance of the app structure app := NewApp() // Create application with options err := wails.Run(&options.App{ Title: "helloworld", Width: 1024, Height: 768, AssetServer: &assetserver.Options{ Assets: assets, Handler: NewFileLoader(), }, BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 255}, OnStartup: app.startup, Bind: []interface{}{ app, }, }) if err != nil { println("Error:", err) } } ``` 当我们在开发模式使用 `wails dev` 运行应用程序时,我们将看到以下输出: ``` DEB | [ExternalAssetHandler] Loading 'http://localhost:3001/favicon.ico' DEB | [ExternalAssetHandler] Loading 'http://localhost:3001/favicon.ico' failed, using AssetHandler Requesting file: favicon.ico ``` 如您所见,当默认资产服务器无法提供 `favicon.ico` 文件时,将调用资产处理程序。 如果您右键单击主应用程序并选择“检查”以调出开发工具,您可以通过在控制台中输入以下内容来测试此功能: ``` let response = await fetch('does-not-exist.txt'); ``` 这将在 devtools 中产生错误。 我们可以看到错误是我们所期望的,由我们的自定义资产处理程序返回: ```mdx-code-block