首页  >  文章  >  后端开发  >  如何处理单页应用程序的 Go 静态文件服务器中的文件未找到异常?

如何处理单页应用程序的 Go 静态文件服务器中的文件未找到异常?

Patricia Arquette
Patricia Arquette原创
2024-10-28 02:32:02775浏览

How to Handle File Not Found Exceptions in a Go Static File Server for Single-Page Applications?

在 Go 静态文件服务器中处理文件未找到异常

在 Go 应用程序中,您正在利用单页 Web 应用程序并使用静态文件服务器提供其资源文件服务器。虽然服务器可以很好地为根目录中的现有资源提供服务,但如果请求的文件不存在,它会抛出 404 Not Found 错误。

您的目标是修改服务器的行为,以便为任何内容提供 index.html无法识别的网址。这一点至关重要,因为您的单页应用程序根据所提供的 HTML 和 JavaScript 处理渲染。

自定义未找到文件处理

http.FileServer() 提供的默认处理程序缺少自定义选项,包括处理 404 未找到响应。为了解决这个限制,我们将包装处理程序并在包装器中实现我们的逻辑。

制作自定义 HTTP 响应编写器

我们将创建一个包装原始内容的自定义 http.ResponseWriter回复作家。此自定义响应编写器将:

  1. 检查响应状态,特别是查找 404 状态代码。
  2. 如果检测到 404 状态代码,而不是向客户端发送响应,我们将发送 302 Found 重定向响应到 /index.html。

下面是此类自定义响应编写器的示例:

<code class="go">type NotFoundRedirectRespWr struct {
    http.ResponseWriter // Embed the base HTTP response writer
    status              int
}

func (w *NotFoundRedirectRespWr) WriteHeader(status int) {
    w.status = status // Store the status code
    if status != http.StatusNotFound {
        w.ResponseWriter.WriteHeader(status) // Proceed normally for non-404 statuses
    }
}

func (w *NotFoundRedirectRespWr) Write(p []byte) (int, error) {
    if w.status != http.StatusNotFound {
        return w.ResponseWriter.Write(p) // Proceed normally for non-404 statuses
    }
    return len(p), nil // Pretend that the data was successfully written, but discard it
}</code>

包装默认处理程序

接下来,我们包装 http.FileServer() 返回的处理程序。包装器处理程序将:

  1. 调用默认处理程序。
  2. 如果默认处理程序在我们的自定义响应编写器中设置 404 状态代码,则此包装器将拦截响应。
  3. 它不会发送 404 响应,而是将请求重定向到 /index.html,状态为 302 Found。

以下是包装处理程序的示例:

<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) // Call the default handler with our custom response writer
        if nfrw.status == 404 {
            log.Printf("Redirecting %s to index.html.", r.RequestURI)
            http.Redirect(w, r, "/index.html", http.StatusFound)
        }
    }
}</code>

将它们放在一起

现在,在 main() 函数中,利用包装处理程序来修改静态文件服务器的行为。

<code class="go">func main() {
    fs := wrapHandler(http.FileServer(http.Dir("."))) // Wrap the handler
    http.HandleFunc("/", fs)
    panic(http.ListenAndServe(":8080", nil)) // Start serving files with the custom handler
}</code>

通过这种方法,所有对与不存在的文件相对应的 URL 的请求将触发到 index.html 的重定向。您的单页应用程序将按预期运行,根据所提供的 HTML 和 JavaScript 呈现适当的内容。

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

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