首页 > 解决方案 > go 1.16 embed - 去除目录名

问题描述

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

使用 Go 1.16,我可以删除该 deps

例如:

//go:embed static
var static embed.FS

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

这将为./static/目录提供服务http://.../static/

有没有一种方法可以从/根路径提供该目录,而不需要/static

标签: go

解决方案


使用fs.Sub

Sub 返回对应于以 fsys 目录为根的子树的 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

推荐阅读