go - 嵌入目录中的 index.html 在哪里?

标签 go webserver single-page-application

我正在尝试 embed一个静态站点(和 SPA)到我的 Go 代码中。我的项目的高层结构是

.
├── web.go
└── spa/
    └── index.html
我的意图是拥有 http://localhost:8090/服务 index.html .
执行此操作的相关代码是
//go:embed spa
var spa embed.FS

log.Info("starting api server")
r := mux.NewRouter()
r.Handle("/", http.FileServer(http.FS(spa)))
log.Fatal(http.ListenAndServe(":8090", r))
访问时http://localhost:8090/ ,我得到
  • 带有单个链接的目录列表页面 spa
  • 单击此链接后,我会收到 404 page not found

  • 我应该如何设置?

    最佳答案

    嵌入目录中的文件路径以//go:embed 指令中使用的路径为前缀。 index.html 的内嵌文件系统路径是 spa/index.html .
    Create a sub file system Root 于spa目录并为该文件系统提供服务。 index.html 的路径在子文件系统中是 index.html .

    sub, _ := fs.Sub(spa, "spa")
    r.Handle("/", http.FileServer(http.FS(sub)))
    
    https://pkg.go.dev/io/fs#Sub
    Run an example on the playground .
    这种方法适用于任何多路复用器,包括 gorilla 多路复用器。这是 Gorilla 的代码,其中 r*mux.Router :
    sub, _ := fs.Sub(spa, "spa")
    r.PathPrefix("/").Handler(http.FileServer(http.FS(sub)))
    
    Run an example on the playground

    关于go - 嵌入目录中的 index.html 在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67232525/

    相关文章:

    redirect - Golang 重定向 fmt.Scanf 以从文件而不是 os.Stdin 读取

    google-app-engine - 如何在社交网络环境中使用内存缓存?

    javascript - 我们是否需要 Web 服务器(如 Apache)来访问 .json 文件?

    Golang : pointer to function from string (function's name)

    go - 水牛中的反向路由

    php - PHP 可以异步使用套接字吗?

    angularjs - Google NoCaptcha ReCaptcha 仅在 Angular SPA 中刷新时显示

    regex - Apache 使用 AliasMatch 与 WSGI 进程一起提供单页应用程序

    node.js - Angular2 POST Observable 请求返回不可读的 JSON 对象

    arrays - 将列表解码为集合