【问题标题】:go 1.16 embed - strip directory namego 1.16 embed - 去除目录名
【发布时间】:2021-02-25 21:42:52
【问题描述】:

我之前使用 statik 将文件嵌入到 Go 应用程序中。

在 Go 1.16 中,我可以删除那些依赖

例如:

//go:embed static
var static embed.FS

fs := http.FileServer(http.FS(static))
http.Handle("/", fs)

这将提供来自http://.../static/./static/ 目录

有没有办法可以从 / 根路径提供该目录,而无需 /static

【问题讨论】:

    标签: go


    【解决方案1】:

    使用fs.Sub:

    Sub 返回一个对应于以 fsys 的 dir 为根的子树的 FS。

    package main
    
    import (
            "embed"
            "io/fs"
            "log"
            "net/http"
    )
    
    //go:embed static
    var static embed.FS
    
    func main() {
            subFS, _ := fs.Sub(static, "static")
    
            http.Handle("/", http.FileServer(http.FS(subFS)))
    
            log.Fatal(http.ListenAndServe(":4000", nil))
    }
    

    fs.Sub 还可以与http.StripPrefix 结合使用以“重命名”目录。例如,将静态目录“重命名”为 public,这样对 /public/index.html 的请求就会为 static/index.html 服务:

    //go:embed static
    var static embed.FS
    
    subFS, _ := fs.Sub(static, "static")
    http.Handle("/", http.StripPrefix("/public", http.FileServer(http.FS(subFS))))
    

    或者,在静态目录中创建一个 .go 文件并将 embed 指令移到那里 (//go:embed *)。这更接近于 statik 工具所做的事情(它创建一个全新的包),但由于 fs.Sub,通常是不必要的。

    // main.go
    package main
    
    import (
        "my.module/static"
        "log"
        "net/http"
    )
    
    func main() {
        http.Handle("/", http.FileServer(http.FS(static.FS)))
    
        log.Fatal(http.ListenAndServe(":4000", nil))
    }
    
    // static/static.go
    package static
    
    import "embed"
    
    //go:embed *
    var FS embed.FS
    

    【讨论】:

      猜你喜欢
      • 2010-11-23
      • 1970-01-01
      • 2022-01-19
      • 2014-12-08
      • 2022-07-04
      • 2022-11-19
      • 2021-08-26
      • 2021-10-19
      • 2021-05-22
      相关资源
      最近更新 更多