【发布时间】:2015-05-01 20:24:25
【问题描述】:
我有点困惑。许多示例显示了两者的用法:http.ServeFile(..) 和 http.FileServer(..),但似乎它们具有非常接近的功能。我也没有找到有关如何设置自定义 NotFound 处理程序的信息。
// This works and strip "/static/" fragment from path
fs := http.FileServer(http.Dir("static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
// This works too, but "/static2/" fragment remains and need to be striped manually
http.HandleFunc("/static2/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, r.URL.Path[1:])
})
http.ListenAndServe(":8080", nil)
我尝试阅读源代码,它们都使用serveFile(ResponseWriter, *Request, FileSystem, string, bool) 底层函数。但是http.FileServer 使用自己的ServeHTTP() 方法返回fileHandler,并在提供文件之前做一些准备工作(例如path.Clean())。
那么为什么需要这种分离呢?哪种方法更好用?以及如何设置自定义 NotFound 处理程序,例如在未找到请求的文件时?
【问题讨论】:
-
最大的区别是
http.FileServer是http.Handler,而http.ServeFile不是。 -
谢谢,我知道,但这并没有让我的困境变得更好)