之前的文章说到用golang开发静态资源服务器
现在遇到个问题,访问目录是会列目录。为了安全需要禁止这个功能。
先看资源服务器代码
package main
import (
"net/http"
)
func main() {
http.Handle("/static", http.StripPrefix("/static", http.FileServer(http.Dir("./static"))))
http.ListenAndServe("127.0.0.1:8080",nil)
}
go run server.go
运行之后打开连接http://127.0.0.1:8080/static
发现已经列目录
这时候我们需要自己实现http.FileSystem禁止列目录
代码如下
package main
import (
"net/http"
"errors"
"os"
)
type disableDirFileSystem struct {
fs http.FileSystem
}
func (fs disableDirFileSystem) Open(name string )(http.File,error) {
f,err := fs.fs.Open(name)
if err != nil {
return nil,err
}
return disableDirFile{File:f},nil
}
type disableDirFile struct {
http.File
}
func (d disableDirFile) Stat()(os.FileInfo,error) {
s,err := d.File.Stat()
if err != nil {
return nil,err
}
if s.IsDir() {
// 如果是目录则不显示
return nil,errors.New("disable")
}
return s,err
}
func main() {
f := disableDirFileSystem{
fs: http.Dir("./static"),
}
http.Handle("/static", http.StripPrefix("/static", http.FileServer(f)))
http.ListenAndServe("127.0.0.1:8080",nil)
}
这时候再访问目录已经不能列目录了
the end