卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章34401本站已运行393

如何在 Golang 中重写 40​​4

如何在 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.ListenAndServe 的文档:

如果 handler 为 nil,则将使用默认处理程序 http.HandleFunc

因此,在您的代码中,您使用 DefaultServeMux 注册了两条路由;调用 http.ListenAndServe(":80", nil) 使用默认处理程序(您添加了路由),因此 /test 可以工作(更多信息如下!)。但是,当您运行 http.ListenAndServe(":80", fs) 时,您将传入一个特定的处理程序 (fs),因此所有请求都将发送到该处理程序(它将尝试从本地文件系统提供文件)。

从这一点开始,我将假设 http.ListenAndServe(":80", nil) 正在被使用(因为添加处理程序然后不使用它们并没有真正意义)。

上面提到的ServeMux所以让我们检查一下该文档:

因此,Mux 接收请求并计算出应该调用哪个处理程序来处理该请求(请注意,只会调用一个处理程序)。匹配基于模式的长度(因此,在您的示例中 /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重定向到前端路由?
  • 卓越飞翔博客
    上一篇: 如何从 go 中的 os.exec 获取输出
    下一篇: 返回列表
    留言与评论(共有 0 条评论)
       
    验证码:
    隐藏边栏