登录
首页 >  Golang >  Go问答

阻止目录列表在 Go Public 文件夹中显示

来源:stackoverflow

时间:2024-02-14 23:18:20 130浏览 收藏

本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《阻止目录列表在 Go Public 文件夹中显示》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~

问题内容

我正在使用 nginx 后面的文件,我的公共文件夹很好......有点太公开了:

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/images,我想删除目录列表 所以例如/public/css/main.css 可以工作,但 /public/ 或 /public/css 不行


正确答案


如果路径有尾部斜杠(即,如果它是目录),您可以实现自定义中间件以返回 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 Public 文件夹中显示》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>