为了账号安全,请及时绑定邮箱和手机立即绑定

如何从 go embed 中提供文件

如何从 go embed 中提供文件

Go
婷婷同学_ 2022-10-17 10:08:15
我有一个静态目录,其中包含一个sign.html文件://go:embed staticvar static embed.FS它以这种方式提供并且工作正常:fSys, err := fs.Sub(static, "static")if err != nil {    return err}mux.Handle("/", http.FileServer(http.FS(fSys)))不过,在某些路线上(例如:)/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}不幸的是,ServeFile没有找到显示器。如何在其中从文件服务器提供文件ServeSignPage?
查看完整描述

1 回答

?
隔江千里

TA贡献1906条经验 获得超10个赞

选项1

将文件读入一个字节片。 将字节写入响应。

p, err := static.ReadFile("static/sign.html")

if err != nil {

    // TODO: Handle error as appropriate for the application.

}

w.Write(p)

选项 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)))

}

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


 mux.Handle("/", staticServer)

委托给静态服务器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

}


查看完整回答
反对 回复 2022-10-17
  • 1 回答
  • 0 关注
  • 63 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信