防止在 Go Public 文件夹中列出目录
Prevent Directory Listing in Go Public Folder
我正在使用 go behind nginx,我的 public 文件夹很好..有点太 public:
func main() {
defer db.Close()
// public dir is /public
fs := http.FileServer(http.Dir("public"))
http.Handle("/public/", http.StripPrefix("/public/", fs))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {..
如果访问者只需键入 mydomain/public,它就可以访问整个 public 文件夹和。查看所有文件。我想保持对文件的访问权限(显然),但如果您只键入 /public 或 /public/images 我想删除目录列表
所以例如/public/css/main.css 可以,但不能 /public/ 或 /public/css
如果路径有尾部斜杠(即如果它是一个目录),您可以将自定义中间件实现到 return 404。
func intercept(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/") {
http.NotFound(w, r)
return
}
next.ServeHTTP(w, r)
})
}
func main() {
defer db.Close()
// public dir is /public
fs := http.FileServer(http.Dir("public"))
http.Handle("/public/", http.StripPrefix("/public", intercept(fs)))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {...}
...
}
此外,对任何没有尾部斜杠的目录的请求将被重定向以接收 404 响应。
我正在使用 go behind nginx,我的 public 文件夹很好..有点太 public:
func main() {
defer db.Close()
// public dir is /public
fs := http.FileServer(http.Dir("public"))
http.Handle("/public/", http.StripPrefix("/public/", fs))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {..
如果访问者只需键入 mydomain/public,它就可以访问整个 public 文件夹和。查看所有文件。我想保持对文件的访问权限(显然),但如果您只键入 /public 或 /public/images 我想删除目录列表 所以例如/public/css/main.css 可以,但不能 /public/ 或 /public/css
如果路径有尾部斜杠(即如果它是一个目录),您可以将自定义中间件实现到 return 404。
func intercept(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/") {
http.NotFound(w, r)
return
}
next.ServeHTTP(w, r)
})
}
func main() {
defer db.Close()
// public dir is /public
fs := http.FileServer(http.Dir("public"))
http.Handle("/public/", http.StripPrefix("/public", intercept(fs)))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {...}
...
}
此外,对任何没有尾部斜杠的目录的请求将被重定向以接收 404 响应。