gpt4 book ai didi

http - 使用 http.FileServer 处理自定义 404 页面

转载 作者:行者123 更新时间:2023-12-01 21:17:32 25 4
gpt4 key购买 nike

我目前正在使用基本的 http.FileServer设置为提供一个简单的静态站点。我需要使用自定义未找到页面来处理 404 错误。我一直在研究这个问题,但我无法确定最好的解决方案是什么。
我已经看到了一些关于 GitHub 问题的回复,内容如下:

You can implement your own ResponseWriter which writes a custom message after WriteHeader.


这似乎是最好的方法,但我有点不确定这将如何实现。如果有此实现的任何简单示例,将不胜感激!

最佳答案

我认为这可以用你自己的中间件来解决。您可以先尝试打开该文件,如果它不存在,请调用您自己的 404 处理程序。否则,只需将调用分派(dispatch)到标准库中的静态文件服务器。
这是看起来的样子:

package main

import (
"fmt"
"net/http"
"os"
"path"
)

func notFound(w http.ResponseWriter, r *http.Request) {
// Here you can send your custom 404 back.
fmt.Fprintf(w, "404")
}

func customNotFound(fs http.FileSystem) http.Handler {
fileServer := http.FileServer(fs)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, err := fs.Open(path.Clean(r.URL.Path)) // Do not allow path traversals.
if os.IsNotExist(err) {
notFound(w, r)
return
}
fileServer.ServeHTTP(w, r)
})
}

func main() {
http.ListenAndServe(":8080", customNotFound(http.Dir("/path/to/files")))
}

关于http - 使用 http.FileServer 处理自定义 404 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62747416/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com