func main() {
mux := http.NewServeMux()
staticHandler := http.FileServer(http.Dir("./templates"))
mux.Handle("/", http.StripPrefix("/", staticHandler))
log.Fatal(http.ListenAndServe(":8080", mux))
}
我想加載一個位于“模板”目錄中的 html 檔案。如果“模板”中有多個檔案,如何選擇要加載的某個檔案?
uj5u.com熱心網友回復:
您可以使用它http.ServeFile()來構建自己的檔案服務器。
見下圖。
然后,您可以在您的 custom 中攔截提供的檔案fileHandler.ServeHTTP()。
package main
import (
"log"
"net/http"
"path"
"path/filepath"
"strings"
)
func main() {
mux := http.NewServeMux()
//staticHandler := http.FileServer(http.Dir("./templates"))
staticHandler := fileServer("./templates")
mux.Handle("/", http.StripPrefix("/", staticHandler))
log.Printf("listening")
log.Fatal(http.ListenAndServe(":8080", mux))
}
// returns custom file server
func fileServer(root string) http.Handler {
return &fileHandler{root}
}
// custom file server
type fileHandler struct {
root string
}
func (f *fileHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
upath := r.URL.Path
if !strings.HasPrefix(upath, "/") {
upath = "/" upath
r.URL.Path = upath
}
name := filepath.Join(f.root, path.Clean(upath))
log.Printf("fileHandler.ServeHTTP: path=%s", name)
http.ServeFile(w, r, name)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/464595.html
上一篇:計算跳過節假日和周末的作業日
