<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 (
"net/http"
"log"
)
func main(){
http.Handle("/", http.FileServer(http.Dir("./static")))
http.ListenAndServe(":8080", 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>'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'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's Open method ...
path := filepath.Join(dir, filepath.FromSlash(path.Clean("/"+name)))
f, err := os.Open(path)
if err != nil {
if os.IsNotExist(err) && strings.HasSuffix(path, "/index.html") {
return CustomDirIndex(strings.TrimSuffix(path, "index.html"))
}
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>"index.html"</code>.</p>
<p>I'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'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'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's not like FileServer is that complicated either.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传