栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用go static文件服务器时,如何自定义处理找不到的文件?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用go static文件服务器时,如何自定义处理找不到的文件?

返回的处理程序

http.FileServer()
不支持自定义,它不支持提供自定义404页面或操作。

我们可以做的是包装由返回的处理程序

http.FileServer()
,并且在我们的处理程序中,我们当然可以做我们想做的任何事情。在包装器处理程序中,我们将调用文件服务器处理程序,如果该处理程序将发送
404
未找到的响应,则不会将其发送给客户端,而是将其替换为重定向响应。

为此,我们在包装器中创建了一个包装器

http.ResponseWriter
,该包装器将传递给由返回的处理程序
http.FileServer()
,在该包装器响应编写器中,我们可以检查状态代码,如果是
404
,我们可以采取行动
将响应发送给客户端,而是将重定向发送到
/index.html

这是一个示例,该包装器

http.ResponseWriter
可能如下所示:

type NotFoundRedirectRespWr struct {    http.ResponseWriter // We 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}

并包装返回的处理程序

http.FileServer()
可能如下所示:

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)        }    }}

请注意,我使用的是

http.StatusFound
重定向状态代码,而不是
http.StatusMovedPermanently
后者,因为后者可能被浏览器缓存,因此,如果稍后创建具有该名称的文件,浏览器将不会请求它,而是
index.html
立即显示。

现在使用该

main()
功能:

func main() {    fs := wrapHandler(http.FileServer(http.Dir(".")))    http.HandleFunc("/", fs)    panic(http.ListenAndServe(":8080", nil))}

尝试查询不存在的文件,我们将在日志中看到以下内容:

2017/11/14 14:10:21 Redirecting /a.txt3 to /index.html.2017/11/14 14:10:21 Redirecting /favicon.ico to /index.html.

请注意,我们的自定义处理程序(行为良好)还将请求重定向到

/favico.ico
index.html
因为
favico.ico
我的文件系统中没有文件。如果您也没有,可以将其添加为例外。

完整的示例可在GoPlayground上找到。您无法在此处运行它,将其保存到本地Go工作区中并在本地运行。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/413140.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号