Golang静态文件夹路径返回所有文件

huangapple go评论82阅读模式
英文:

Golang Static folder path returns all files

问题

我有一个用于打开静态文件夹的代码:

fs := http.FileServer(http.Dir("./static/"))
router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", fs))

但是当我访问/static路径时,它返回了该文件夹中的文件列表,例如:

license.txt
logo.png

但我想返回一个空白页面。

英文:

i have a this code to open static folder

fs := http.FileServer(http.Dir("./static/"))
router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", fs))

but when i'm going to /static path it returns a list of files in this folder

eg

license.txt
logo.png

but i want to return a blank page

答案1

得分: 1

你可以在目录./static/中添加一个空白的index.html文件,它将被渲染为空白页面。

类似于这样:

<html>
<head><title>这里什么都没有</title></head>
<body><h1>这里什么都没有</h1></body>
</html>
英文:

You can add blank index.html in directory ./static/, it will be rendered as blank page.

Something like this

&lt;html&gt;
&lt;head&gt;&lt;title&gt;Nothing here&lt;/title&gt;&lt;/head&gt;
&lt;body&gt;&lt;h1&gt;Nothing here&lt;/h1&gt;&lt;/body&gt;
&lt;/html&gt;

</details>



# 答案2
**得分**: 0

vodolaz095的答案是最简单的,但如果你真的必须在Go中完成,你可以包装`FileServer`来捕获请求根目录的特定情况:

```go
func noIndex(fs http.Handler) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        if r.URL.Path == "" || strings.HasSuffix(r.URL.Path, "/") {
            w.Write("")
            return
        }
        fs.ServeHTTP(w, r)
    }
}

请注意,这不会捕获URL中没有尾部斜杠的子目录的请求;要捕获这种情况,你需要一个更详细的自定义实现,它需要了解文件系统,知道什么是目录,什么是文件。

英文:

vodolaz095's answer is the simplest, but if you really must do it in Go, you could wrap the FileServer to catch the specific case of a request for the root:

func noIndex(fs http.Handler) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == &quot;&quot; || strings.HasSuffix(r.URL.Path, &quot;/&quot;) {
			w.Write(&quot;&quot;)
			return
		}
		fs.ServeHTTP(w, r)
	}
}

Note that this doesn't catch requests for subdirectories without a trailing slash in the URL; to trap this you'd need a much more detailed custom implementation that was filesystem-aware to know what is a directory and what is a file.

答案3

得分: 0

看起来你正在使用gorilla/mux,但如果你不介意使用标准库的http.ServeMux,你可以在Go代码中这样实现:

func main() {
    fs := http.FileServer(http.Dir("./static/"))
    h := http.NewServeMux()

    blank := http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {})

    h.Handle("/static/", http.StripPrefix("/static/", fs)) // 匹配"/static"并重定向...
    h.Handle("/static", blank)                             // ...除非你显式地创建一个处理程序

    http.ListenAndServe(":8080", h)
}

来自http.ServeMux文档:

...如果已经注册了一个子树,并且收到了一个不带尾部斜杠的子树根的请求,ServeMux会将该请求重定向到子树根(添加尾部斜杠)。可以通过单独为不带尾部斜杠的路径注册来覆盖此行为。例如,注册"/images/"会导致ServeMux将对"/images"的请求重定向到"/images/",除非"/images"已经单独注册。

英文:

It looks like you are using gorilla/mux - but if you don't mind using the standard library's http.ServeMux you can achieve this in Go code like so:

func main() {

	fs := http.FileServer(http.Dir(&quot;./static/&quot;))
	h := http.NewServeMux()

	blank := http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {})

	h.Handle(&quot;/static/&quot;, http.StripPrefix(&quot;/static/&quot;, fs)) // will match &quot;/static&quot; with a redirect ...
	h.Handle(&quot;/static&quot;, blank)                             // ... unless you create a hanlder explicitly

	http.ListenAndServe(&quot;:8080&quot;, h)
}

from http.ServeMux docs:

> ...if a subtree has been registered and a request is received naming
> the subtree root without its trailing slash, ServeMux redirects that
> request to the subtree root (adding the trailing slash). This behavior
> can be overridden with a separate registration for the path without
> the trailing slash. For example, registering "/images/" causes
> ServeMux to redirect a request for "/images" to "/images/", unless
> "/images" has been registered separately.

huangapple
  • 本文由 发表于 2021年9月3日 03:55:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/69036328.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定