Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Golang Mux路由器和http.FileServer,需要根文件和自定义404_Go_Routing_Http Status Code 404_Mux - Fatal编程技术网

使用Golang Mux路由器和http.FileServer,需要根文件和自定义404

使用Golang Mux路由器和http.FileServer,需要根文件和自定义404,go,routing,http-status-code-404,mux,Go,Routing,Http Status Code 404,Mux,我正在Go中建立一个小网站,自定义404页面有问题。这是我当前的路由器代码: r := mux.NewRouter() // Page routing r.HandleFunc("/", homeHandler).Methods("GET") r.HandleFunc("/example1", exampleOneHandler).Methods("GET") r.HandleFunc("/example2", exampleTwoHandler).Methods("GET", "POST")

我正在Go中建立一个小网站,自定义404页面有问题。这是我当前的路由器代码:

r := mux.NewRouter()

// Page routing
r.HandleFunc("/", homeHandler).Methods("GET")
r.HandleFunc("/example1", exampleOneHandler).Methods("GET")
r.HandleFunc("/example2", exampleTwoHandler).Methods("GET", "POST")

// Other paths for static assets omitted

// Psuedo-root directory for icon files, etc.
r.PathPrefix("/").Handler(http.FileServer(http.Dir("public")))

// 404 Page
r.NotFoundHandler = http.HandlerFunc(notFoundHandler)

log.Fatal(http.ListenAndServe(":1234", r))
因此,如果第11行没有PathPrefix定义,notFoundHandler将按预期命中并返回自定义404HTML

但是,现在我添加了路径定义,以满足根目录标准,如favicon.ico、robots.txt、app icons等,并按预期工作。但是,作为一个副作用,任何与/example1或/example2不匹配的内容,比如说/example3,都将通过http.FileServer在psuedo根目录中查找名为“example3”的文件。在找不到它之后,文件服务器直接向http.ResponseWriter写入“404notfound”,完全绕过mux的NotFoundHandler


我能看到的唯一可行的解决方案是为每个文件添加显式路由,但这似乎是一个相当残酷的解决方案。有没有更优雅的方法来解决我所缺少的这个问题?

对于没有注册处理程序的路径,会激活
notFoundHandler
。由于您已将处理程序(文件服务器)注册到路径
“/”
,该路径将始终匹配所有请求,因此将不再调用未找到的处理程序

要避免这种情况,最简单的方法是手动注册所有必须在根目录下的文件(这些文件不多,或者至少不应该有)。如果您有一堆其他非标准静态文件,请将它们发布到类似于
/static/
的路径下,这样未注册的路径(例如
/example3
)将触发未找到的处理程序

另一种解决方案是将文件服务器保留在路径
“/”
,但将其包装,如果它将返回
404
状态代码,请调用您自己的
notFoundHandler
以提供自定义错误页。这比我之前的建议更复杂,所以我还是同意这个建议