Custom 404 page while serving files?

blov · · 717 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I&#39;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&#39;s still giving me the default 404 page when I go to a page that doesn&#39;t exist. Here&#39;s what I have so far:</p> <pre><code>package main import ( &#34;net/http&#34; &#34;github.com/julienschmidt/httprouter&#34; ) func main() { router := httprouter.New() router.NotFound = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, &#34;static/404.html&#34;) }) router.ServeFiles(&#34;/*filepath&#34;, http.Dir(&#34;static&#34;)) http.ListenAndServe(&#34;:8080&#34;, 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&#39;s NotFound handler.<br/> To use the operating system&#39;s file system implementation,<br/> use http.Dir:<br/> router.ServeFiles(&#34;/src/*filepath&#34;, http.Dir(&#34;/var/www&#34;)) </p> </blockquote> <p>In other words, you need to either use a different router library that doesn&#39;t have this property, or just don&#39;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&#39;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

717 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传