首页  >  文章  >  后端开发  >  如何在 Go 静态文件服务器中将 404 错误重定向到 Index.html?

如何在 Go 静态文件服务器中将 404 错误重定向到 Index.html?

DDD
DDD原创
2024-10-28 05:29:30584浏览

How to Redirect 404 Errors to Index.html in a Go Static File Server?

使用静态文件服务器时如何处理丢失文件错误?

使用 FileServer 方法从本地目录提供静态文件时,所有资源根路由已正确提供。例如,对于 myserverurl/index.html 和 myserverurl/styles.css 的请求,提供 index.html 和 style.css 不会出现任何问题。但是,如果向没有相应文件的路由发出请求,则会返回 404 错误。

要为所有此类路由提供 index.html 并呈现适当的屏幕,可以使用自定义处理程序创建用于包装 FileServer 处理程序。

创建包装器

包装器处理程序创建一个包装器 http.ResponseWriter,并将其传递给 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
}

使用此包装器来包装 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)
        }
    }
}

然后注册包装的处理程序来处理请求:

func main() {
    fs := wrapHandler(http.FileServer(http.Dir(".")))
    http.HandleFunc("/", fs)
    panic(http.ListenAndServe(":8080", nil))
}

尝试查询不存在的文件,如 /a.txt3 或 favicon.ico,将导致404 错误并且请求被重定向到 /index.html。

以上是如何在 Go 静态文件服务器中将 404 错误重定向到 Index.html?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn