1 回答
TA贡献1818条经验 获得超7个赞
您可以使用它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)
}
- 1 回答
- 0 关注
- 110 浏览
添加回答
举报