Adding a filesize to FileServer

agolangf · · 398 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Would it be possible to add file size, in bytes, to FileServer? Or would I need to use a different method? Here is my code: package main</p> <pre><code>import ( &#34;net/http&#34; &#34;log&#34; ) func main(){ http.Handle(&#34;/&#34;, http.FileServer(http.Dir(&#34;./static&#34;))) http.ListenAndServe(&#34;:8080&#34;, nil) } </code></pre> <hr/>**评论:**<br/><br/>dchapes: <pre><p>No. The directory listings <code>http.FileServer</code> generates come from <code>net/http/fs.go</code>&#39;s <code>dirList</code> function and is hard coded and non-replaceable.</p> <p>There are probably several ways you can do customized directory listings.</p> <p>In the past I&#39;ve done it by implementing my own <code>http.FileSystem</code> in place of <code>http.Dir</code>. To do so, look at the existing implementation of <code>http.Dir</code> and just change yours to do something like this at the end:</p> <pre><code>// ... other stuff from http.Dir&#39;s Open method ... path := filepath.Join(dir, filepath.FromSlash(path.Clean(&#34;/&#34;+name))) f, err := os.Open(path) if err != nil { if os.IsNotExist(err) &amp;&amp; strings.HasSuffix(path, &#34;/index.html&#34;) { return CustomDirIndex(strings.TrimSuffix(path, &#34;index.html&#34;)) } return nil, err } return f, nil </code></pre> <p>Where <code>CustomDirIndex</code> is given a directory name and returns a <code>http.File</code> that produces output formated however you like. This works because before <code>serveFile</code> calls <code>dirList</code> it first tries to open <code>&#34;index.html&#34;</code>.</p> <p>I&#39;ve implemented that part with a struct that embeds a <code>*bytes.Reader</code> (for the <code>io.Reader</code> and <code>io.Seeker</code> parts of the <code>http.File</code> interface; I fill this at creation time by executing a template), an <code>os.FileInfo</code> that can be used to implement the <code>Stat()</code> method (with care taken to return the reader&#39;s <code>Len</code> in place of <code>Size</code>) and finally NOP <code>Close()</code> and <code>Readdir()</code> methods.</p></pre>jcbwlkr: <pre><p>Could you clarify what you mean? When <code>http.FileServer</code> serves up a file it includes the <code>Content-Length</code> header with the number of bytes. Do you mean something else?</p></pre>MMFW_: <pre><p>I&#39;m looking to display text with the file size next to the file name</p></pre>interactiv_: <pre><p>No, use something else or rewrite it from Scratch. It&#39;s not like FileServer is that complicated either.</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

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