首页  >  文章  >  后端开发  >  如何在 Golang 中重写 40​​4

如何在 Golang 中重写 40​​4

WBOY
WBOY转载
2024-02-08 21:30:191114浏览

如何在 Golang 中重写 40​​4

在Golang中,重写404错误页面是一个常见的需求,可以帮助我们提供更友好和个性化的错误提示。在本文中,php小编西瓜将向大家介绍如何在Golang中实现404页面的重写。我们将使用Gin框架来搭建Web应用,并通过自定义中间件来处理404错误。通过本文的指导,您将学会如何简单快速地重写404页面,提升用户体验。让我们开始吧!

问题内容

我仍在学习如何使用 Go 进行 Web 开发,但是当我尝试创建一个简单的网站时,我面临以下困难:

package main

import (
   "fmt"
   "html/template"
   "net/http"
)

func main() {

   fs := http.FileServer(http.Dir(""))

   http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
       tmpl, _ := template.ParseFiles("index.html")
       tmpl.Execute(w, nil)
   })

   /**
   *    This route will return a 404 error
   */
   http.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
       fmt.Fprint(w, "Test page")
   })

   /**
   *    If I replace fs to nil, /test route will be work, but non-existent routes
   *    will be return index.html template (home router) instead 404 error. Why?
   */

   http.ListenAndServe(":80", fs)
}

http.FileServerhttp.HandleFunc 之间存在冲突。

例如,当我编写: http.ListenAndServe(":80", nil) 时,所有路由 (http.HandleFunc) 都将工作,但如果我尝试执行以下操作:

http.ListenAndServe(":80", http.FileServer(http.Dir("")))

没有路由有效(除了 http.HandleFunc("/"))。为什么?

如何覆盖 404 错误页面?我希望 Go 有一个像 http.HandleError 这样的方法,它接受 http.ResponseWriterhttp.Request 的接口,但我找不到类似的东西。http.HandleError 这样的方法,它接受 http.ResponseWriterhttp.Request 的接口,但我找不到类似的东西。

解决方法

检查 http.ListenAndServe解决方法

检查 http.ListenAndServehandler 为 nil,则将使用默认处理程序 http.HandleFunc 的文档:

如果

DefaultServeMux 注册了两条路由;调用 http.ListenAndServe(":80", nil) 使用默认处理程序(您添加了路由),因此 /test 可以工作(更多信息如下!)。但是,当您运行 http.ListenAndServe(":80", fs) 时,您将传入一个特定的处理程序 (fs

因此,在您的代码中,您使用 http.ListenAndServe(":80", nil)),因此所有请求都将发送到该处理程序(它将尝试从本地文件系统提供文件)。

从这一点开始,我将假设 正在被使用(因为添加处理程序然后不使用它们并没有真正意义)。ServeMux 上面提到的

/test/ 长,因此优先)。这意味着对 /test 的请求将触发 fmt.Fprint(w, "测试页") ,其他所有内容将调用加载 index.html 的处理程序。需要注意的是,您尚未添加引用 fs所以让我们检查一下该文档:

  • 使用 http.FileServer 处理自定义 404 页面
  • 使用 Golang Mux Router 和 http.FileServer 实现预期的根文件和自定义 404
  • 使用 Gorilla Mux 和 std http.FileServer 的自定义 404
  • Golang。用什么? http.ServeFile(..) 还是 http.FileServer(..)?
  • 如何让golang重定向到前端路由?🎜🎜 🎜

    以上是如何在 Golang 中重写 40​​4的详细内容。更多信息请关注PHP中文网其他相关文章!

    声明:
    本文转载于:stackoverflow.com。如有侵权,请联系admin@php.cn删除