从 URL 的根路径提供嵌入式文件系统

Sam*_*ann 3 go

Go 1.16 添加了新的嵌入包。我想使用这个包来嵌入一个目录并通过 HTTP 提供它。考虑以下设置:

myproject/
|-- main.go
|-- static/
|   |-- index.html
|   |-- styles.css
|   |-- scripts.js
Run Code Online (Sandbox Code Playgroud)
myproject/
|-- main.go
|-- static/
|   |-- index.html
|   |-- styles.css
|   |-- scripts.js
Run Code Online (Sandbox Code Playgroud)

通过此设置,我的期望是我可以将浏览器指向localhost:8080并加载index.html。相反,我观察到的是,我需要将浏览器指向localhost:8080/static加载index.html

如何从 URL 的根路径提供嵌入式文件系统?

Sam*_*ann 9

在声明embed.FS类型的变量时,该变量表示已包含根目录的文件系统。//go:embed指令中的所有资源都被复制到文件系统的这个根目录中。这意味着该staticFS变量不引用static直接嵌入的文件夹,而是引用包含该static文件夹的根目录。考虑到这一点,为了实现能够从 访问static文件夹的预期结果,可以使用localhost:8080Go 的fs.Sub将文件系统传递到文件static夹作为根的服务器:

package main

import (
    "embed"
    "io/fs"
    "log"
    "net/http"
)

//go:embed static
var embeddedFS embed.FS

func main() {
    serverRoot, err := fs.Sub(embeddedFS, "static")
    if err != nil {
        log.Fatal(err)
    }

    http.Handle("/", http.FileServer(http.FS(serverRoot)))
    log.Fatal(http.ListenAndServe(":8080", nil))
}
Run Code Online (Sandbox Code Playgroud)