搜索
首页后端开发Golang如何在 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.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。如有侵权,请联系admin@php.cn删除
    与GO接口键入断言和类型开关与GO接口键入断言和类型开关May 02, 2025 am 12:20 AM

    Gohandlesinterfacesandtypeassertionseffectively,enhancingcodeflexibilityandrobustness.1)Typeassertionsallowruntimetypechecking,asseenwiththeShapeinterfaceandCircletype.2)Typeswitcheshandlemultipletypesefficiently,usefulforvariousshapesimplementingthe

    使用errors.is和错误。使用errors.is和错误。May 02, 2025 am 12:11 AM

    Go语言的错误处理通过errors.Is和errors.As函数变得更加灵活和可读。1.errors.Is用于检查错误是否与指定错误相同,适用于错误链的处理。2.errors.As不仅能检查错误类型,还能将错误转换为具体类型,方便提取错误信息。使用这些函数可以简化错误处理逻辑,但需注意错误链的正确传递和避免过度依赖以防代码复杂化。

    在GO中进行性能调整:优化您的应用程序在GO中进行性能调整:优化您的应用程序May 02, 2025 am 12:06 AM

    tomakegoapplicationsRunfasterandMorefly,useProflingTools,leverageConCurrency,andManageMoryfectily.1)usepprofforcpuorforcpuandmemoryproflingtoidentifybottlenecks.2)upitizegorizegoroutizegoroutinesandchannelstoparalletaparelalyizetasksandimproverperformance.3)

    GO的未来:趋势和发展GO的未来:趋势和发展May 02, 2025 am 12:01 AM

    go'sfutureisbrightwithtrendslikeMprikeMprikeTooling,仿制药,云 - 纳蒂维德象,performanceEnhancements,andwebassemblyIntegration,butchallengeSinclainSinClainSinClainSiNgeNingsImpliCityInsImplicityAndimimprovingingRornhandRornrorlling。

    了解Goroutines:深入研究GO的并发了解Goroutines:深入研究GO的并发May 01, 2025 am 12:18 AM

    goroutinesarefunctionsormethodsthatruncurranceingo,启用效率和灯威量。1)shememanagedbodo'sruntimemultimusingmultiplexing,允许千sstorunonfewerosthreads.2)goroutinessimproverentimensImproutinesImproutinesImproveranceThroutinesImproveranceThrountinesimproveranceThroundinesImproveranceThroughEasySytaskParallowalizationAndeff

    了解GO中的初始功能:目的和用法了解GO中的初始功能:目的和用法May 01, 2025 am 12:16 AM

    purposeoftheInitfunctionoIsistoInitializeVariables,setUpConfigurations,orperformneccesSetarySetupBeforEtheMainFunctionExeCutes.useInitby.UseInitby:1)placingitinyourcodetorunautoamenationally oneraty oneraty oneraty on inity in ofideShortAndAndAndAndForemain,2)keepitiTshortAntAndFocusedonSimImimpletasks,3)

    了解GO界面:综合指南了解GO界面:综合指南May 01, 2025 am 12:13 AM

    Gointerfacesaremethodsignaturesetsthattypesmustimplement,enablingpolymorphismwithoutinheritanceforcleaner,modularcode.Theyareimplicitlysatisfied,usefulforflexibleAPIsanddecoupling,butrequirecarefulusetoavoidruntimeerrorsandmaintaintypesafety.

    从恐慌中恢复:何时以及如何使用recover()从恐慌中恢复:何时以及如何使用recover()May 01, 2025 am 12:04 AM

    在Go中使用recover()函数可以从panic中恢复。具体方法是:1)在defer函数中使用recover()捕获panic,避免程序崩溃;2)记录详细的错误信息以便调试;3)根据具体情况决定是否恢复程序执行;4)谨慎使用,以免影响性能。

    See all articles

    热AI工具

    Undresser.AI Undress

    Undresser.AI Undress

    人工智能驱动的应用程序,用于创建逼真的裸体照片

    AI Clothes Remover

    AI Clothes Remover

    用于从照片中去除衣服的在线人工智能工具。

    Undress AI Tool

    Undress AI Tool

    免费脱衣服图片

    Clothoff.io

    Clothoff.io

    AI脱衣机

    Video Face Swap

    Video Face Swap

    使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

    热工具

    SublimeText3汉化版

    SublimeText3汉化版

    中文版,非常好用

    VSCode Windows 64位 下载

    VSCode Windows 64位 下载

    微软推出的免费、功能强大的一款IDE编辑器

    Dreamweaver CS6

    Dreamweaver CS6

    视觉化网页开发工具

    Dreamweaver Mac版

    Dreamweaver Mac版

    视觉化网页开发工具

    SublimeText3 Linux新版

    SublimeText3 Linux新版

    SublimeText3 Linux最新版