GOLANG如何使用http.FileServer从模板目录加载某个html文件?


func main() {
mux := http.NewServeMux()
staticHandler := http.FileServer(http.Dir("./templates"))
mux.Handle("/", http.StripPrefix("/", staticHandler))
log.Fatal(http.ListenAndServe(":8080", mux))
}

我想加载一个html文件,这是在'模板'目录。如果"模板"中有多个文件,我如何选择要载入的文件?

您可以使用http.ServeFile()来构建您自己的文件服务器。

见下面的草图

然后您可以在自定义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)
}

最新更新