亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從 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 關注
  • 107 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號