如何从 go embed 提供文件

Ado*_*Ren 8 go

我有一个静态目录,包含一个sign.html文件:

//go:embed static
var static embed.FS
Run Code Online (Sandbox Code Playgroud)

它以这种方式提供并且工作正常:

fSys, err := fs.Sub(static, "static")
if err != nil {
    return err
}
mux.Handle("/", http.FileServer(http.FS(fSys)))
Run Code Online (Sandbox Code Playgroud)

但在某些路线上(例如:)/sign,我想在提供页面之前进行一些检查。这是我的处理程序:

func (h Handler) ServeSignPage(w http.ResponseWriter, r *http.Request) error {
    publicKey := r.URL.Query().Get("publicKey")
    err := h.Service.AuthorizeClientSigning(r.Context(), publicKey)
    if err != nil {
        return err
    }
    // this is where I'd like to serve the embed file
    // sign.html from the static directory
    http.ServeFile(w, r, "sign.html")
    return nil
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,ServeFile没有找到显示器。我如何从其中的文件服务器提供文件ServeSignPage

Cer*_*món 8

选项1

将文件读取为字节片。 将字节写入响应。

p, err := static.ReadFile("static/sign.html")
if err != nil {
    // TODO: Handle error as appropriate for the application.
}
w.Write(p)
Run Code Online (Sandbox Code Playgroud)

选项2

如果处理程序的路径ServeSignPage与文件服务器中的静态文件相同,则委托给文件服务器。

将文件服务器存储在包级变量中。

var staticServer http.Handler

func init() {
    fSys, err := fs.Sub(static, "static")
    if err != nil {
          panic(err)
    }
    staticServer = http.FileServer(http.FS(fSys)))
}
Run Code Online (Sandbox Code Playgroud)

使用静态服务器作为处理程序:

 mux.Handle("/", staticServer)
Run Code Online (Sandbox Code Playgroud)

委托给静态服务器ServeSignPage

func (h Handler) ServeSignPage(w http.ResponseWriter, r *http.Request) error {
    publicKey := r.URL.Query().Get("publicKey")
    err := h.Service.AuthorizeClientSigning(r.Context(), publicKey)
    if err != nil {
        return err
    }
    staticServer.ServeHTTP(w, r)
    return nil
}
Run Code Online (Sandbox Code Playgroud)