<p>I'm wanting to have a custom 404 page display whenever a file is not available in the filesystem. I am using <code>httprouter</code> and have overwritten <code>NotFound</code>, but it's still giving me the default 404 page when I go to a page that doesn't exist. Here's what I have so far:</p>
<pre><code>package main
import (
"net/http"
"github.com/julienschmidt/httprouter"
)
func main() {
router := httprouter.New()
router.NotFound = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "static/404.html")
})
router.ServeFiles("/*filepath", http.Dir("static"))
http.ListenAndServe(":8080", router)
}
</code></pre>
<hr/>**评论:**<br/><br/>the_jester: <pre><p>From the comments in julienschmidt/httprouter for router.ServeFiles:</p>
<blockquote>
<p>// Internally a http.FileServer is used, therefore http.NotFound is used instead<br/>
of the Router's NotFound handler.<br/>
To use the operating system's file system implementation,<br/>
use http.Dir:<br/>
router.ServeFiles("/src/*filepath", http.Dir("/var/www")) </p>
</blockquote>
<p>In other words, you need to either use a different router library that doesn't have this property, or just don't use the ServeFiles method - it is all of 11-lines long, so you can replace it readily.</p>
<p>Edit: See <a href="http://stackoverflow.com/questions/9996767/showing-custom-404-error-page-with-standard-http-package" rel="nofollow">examples here</a> for doing this with the vanilla http package, or with gorilla/mux</p></pre>nhooyr: <pre><p>Write an intercepting response writer like this: <a href="https://gist.github.com/nhooyr/9b7b432496716b364bc3a00f08152387" rel="nofollow">https://gist.github.com/nhooyr/9b7b432496716b364bc3a00f08152387</a></p>
<p>All you need to do is create a handler that wraps router.ServeFiles and set the error handler of interceptingResponseWriter appropriately. If you have more problems, I can cook up a full example.</p></pre>manwith4names: <pre><p>I would love to see a full example! I'm still new to Go and am not sure what a handler like that would look like</p></pre>nhooyr: <pre><p><a href="https://gist.github.com/076c397a761fefded1e580c837c528ea" rel="nofollow">https://gist.github.com/076c397a761fefded1e580c837c528ea</a></p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传