【问题标题】:Handling custom 404 pages with http.FileServer使用 http.FileServer 处理自定义 404 页面
【发布时间】:2020-07-05 23:36:22
【问题描述】:

我目前正在使用基本的http.FileServer 设置来服务于一个简单的静态站点。我需要使用自定义未找到页面来处理 404 错误。我一直在研究这个问题,但我无法确定最佳解决方案是什么。

我看到了一些关于 GitHub 问题的回复,大致如下:

您可以实现自己的ResponseWriter,它在WriteHeader 之后写入自定义消息。

这似乎是最好的方法,但我有点不确定这将如何实际实施。如果有此实现的任何简单示例,将不胜感激!

【问题讨论】:

标签: http go go-http


【解决方案1】:

我认为这可以通过您自己的中间件来解决。您可以先尝试打开该文件,如果它不存在,请调用您自己的 404 处理程序。否则,只需将调用分派到标准库中的静态文件服务器。

这可能是这样的:

package main

import (
    "fmt"
    "net/http"
    "os"
    "path"
)

func notFound(w http.ResponseWriter, r *http.Request) {
    // Here you can send your custom 404 back.
    fmt.Fprintf(w, "404")
}

func customNotFound(fs http.FileSystem) http.Handler {
    fileServer := http.FileServer(fs)
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        _, err := fs.Open(path.Clean(r.URL.Path)) // Do not allow path traversals.
        if os.IsNotExist(err) {
            notFound(w, r)
            return
        }
        fileServer.ServeHTTP(w, r)
    })
}

func main() {
    http.ListenAndServe(":8080", customNotFound(http.Dir("/path/to/files")))
}

【讨论】:

  • 我会使用更简单的东西而不是打开文件(smth likeos.Stat()
猜你喜欢
  • 2019-08-08
  • 2019-01-24
  • 1970-01-01
  • 2015-11-06
  • 2021-10-15
  • 2012-04-16
  • 2014-11-26
  • 2018-11-16
相关资源
最近更新 更多