我有一個靜態目錄,其中包含一個sign.html檔案:
//go:embed static
var 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?
uj5u.com熱心網友回復:
選項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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/364101.html
標籤:走
上一篇:從結構標記驗證回傳自定義錯誤訊息
下一篇:Golanggin傳遞一個默認值
