http.FileServer() 返回的处理程序不支持自定义,不支持提供自定义 404 页面或操作。
我们可以做的是包装http.FileServer()返回的处理程序,在我们的处理程序中我们当然可以做任何我们想做的事情。在我们的包装处理程序中,我们将调用文件服务器处理程序,如果这会发送一个 404 未找到响应,我们将不会将其发送给客户端,而是将其替换为重定向响应。
为了实现这一点,在我们的包装器中,我们创建了一个包装器http.ResponseWriter,我们将把它传递给http.FileServer()返回的处理程序,在这个包装器响应编写器中,我们可以检查状态码,如果它是404,我们可能会不将响应发送给客户端,而是将重定向发送到/index.html。
这是这个包装器http.ResponseWriter 的示例:
type NotFoundRedirectRespWr struct {
http.ResponseWriter // We embed http.ResponseWriter
status int
}
func (w *NotFoundRedirectRespWr) WriteHeader(status int) {
w.status = status // Store the status for our own use
if status != http.StatusNotFound {
w.ResponseWriter.WriteHeader(status)
}
}
func (w *NotFoundRedirectRespWr) Write(p []byte) (int, error) {
if w.status != http.StatusNotFound {
return w.ResponseWriter.Write(p)
}
return len(p), nil // Lie that we successfully written it
}
包装 http.FileServer() 返回的处理程序可能如下所示:
func wrapHandler(h http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
nfrw := &NotFoundRedirectRespWr{ResponseWriter: w}
h.ServeHTTP(nfrw, r)
if nfrw.status == 404 {
log.Printf("Redirecting %s to index.html.", r.RequestURI)
http.Redirect(w, r, "/index.html", http.StatusFound)
}
}
}
请注意,我使用http.StatusFound 重定向状态代码而不是http.StatusMovedPermanently,因为后者可能会被浏览器缓存,因此如果稍后创建具有该名称的文件,浏览器不会请求它,而是显示index.html马上。
现在使用 main() 函数:
func main() {
fs := wrapHandler(http.FileServer(http.Dir(".")))
http.HandleFunc("/", fs)
panic(http.ListenAndServe(":8080", nil))
}
尝试查询不存在的文件,我们将在日志中看到:
2017/11/14 14:10:21 Redirecting /a.txt3 to /index.html.
2017/11/14 14:10:21 Redirecting /favicon.ico to /index.html.
请注意,我们的自定义处理程序(行为良好)还将请求重定向到 /favico.ico 到 index.html,因为我的文件系统中没有 favico.ico 文件。如果您也没有它,您可能希望将其添加为例外。
Go Playground 上提供了完整示例。你不能在那里运行它,把它保存到你本地的 Go 工作区并在本地运行它。
同时检查这个相关问题:Log 404 on http.FileServer