首页 > 后端开发 > Golang > 正文

如何处理单页 Web 应用程序的 Go 静态文件服务器中的 404 错误?

Patricia Arquette
发布: 2024-10-28 01:16:02
原创
147 人浏览过

How to Handle 404 Errors in Go's Static File Server for Single-Page Web Applications?

处理自定义文件服务器中的 404 错误

在单页 Web 应用程序中,必须正确处理丢失的文件以确保流畅的用户体验。当使用 Go 的静态文件服务器 http.FileServer() 时,可以自定义处理 404 错误。

http.FileServer() 的默认行为是针对不存在的文件返回 404 Not Found 响应。要将此类请求重定向到自定义页面,例如index.html,可以创建包装器句柄。

创建包装器响应编写器

包装器响应编写器检查http.FileServer() 处理程序返回的状态代码。如果检测到 404,它会抑制发送响应并准备重定向。

<code class="go">type NotFoundRedirectRespWr struct {
    http.ResponseWriter // 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
}</code>
登录后复制

包装文件服务器处理程序

包装处理程序使用 NotFoundRedirectRespWr检测 404 错误。

<code class="go">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)
        }
    }
}</code>
登录后复制

用法

在 main 函数中,使用包装的处理程序而不是原始的 http.FileServer() 处理程序。

<code class="go">func main() {
    fs := wrapHandler(http.FileServer(http.Dir(".")))
    http.HandleFunc("/", fs)
    panic(http.ListenAndServe(":8080", nil))
}</code>
登录后复制

结果

现在,对不存在文件的请求将被重定向到/index.html。日志将显示:

Redirecting /a.txt3 to /index.html.
Redirecting /favicon.ico to /index.html.
登录后复制

此自定义允许灵活处理静态文件服务中的 404 错误,改善单页 Web 应用程序的用户体验。

以上是如何处理单页 Web 应用程序的 Go 静态文件服务器中的 404 错误?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!