Golang静态停止index.html重定向。

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

golang static stop index.html redirection

问题

package main

import (
  "log"
  "net/http"
)

func main() {
  fs := http.FileServer(http.Dir("."))
  http.Handle("/", http.NotFoundHandler()) // 使用 http.NotFoundHandler() 替代 fs,停止显示 index.html 文件

  log.Println("Listening...")
  http.ListenAndServe(":3000", nil)
}

以上是修改后的代码,使用 http.NotFoundHandler() 替代了 fs,这样服务器将不再显示 index.html 文件。

英文:
package main

import (
  "log"
  "net/http"
)

func main() {
  fs := http.FileServer(http.Dir("."))
  http.Handle("/", fs)

  log.Println("Listening...")
  http.ListenAndServe(":3000", nil)
}

So I have a index.html file and want server to stop showing it.

答案1

得分: 2

FileServer的文档中指出:

> 作为一个特例,返回的文件服务器会将任何以"/index.html"结尾的请求重定向到相同的路径,但不包括最后的"index.html"。

因此,/index.html会被重定向到//foo/bar/index.html会被重定向到/foo/bar/

为了避免这种情况,可以为特殊情况注册一个额外的处理程序。

http.HandleFunc("/index.html", func(w http.ResponseWriter, r *http.Request) {
    f, err := os.Open("index.html")
    if err != nil {
        // 处理错误
        return
    }
    http.ServeContent(w, r, "index.html", time.Now(), f)
})

请注意,我使用的是ServeContent,而不是ServeFile,因为ServeFile会以与FileServer相同的方式处理/index.html请求。

英文:

The docs for FileServer state that:

> As a special case, the returned file server redirects any request
> ending in "/index.html" to the same path, without the final
> "index.html".

So /index.html is redirected to /, /foo/bar/index.html is redirected to /foo/bar/.

To avoid this register an additional handler for the special case.

http.HandleFunc("/index.html", func(w http.ResponseWriter, r *http.Request) {
    f, err := os.Open("index.html")
    if err != nil {
        // handle error
        return
    }
    http.ServeContent(w, r, "index.html", time.Now(), f)
})

Please note I'm using ServeContent insead of ServeFile because ServeFile handles /index.html requests the same way as FileServer.

答案2

得分: 1

没有重定向,当请求一个目录时,默认渲染的文件是 index.html。目录列表是当找不到这个文件时的备选项,所以如果不删除 index.html 文件,就无法获取目录列表。

如果你想要一个目录列表,你需要自己编写,然后可以按照你的选择进行格式化和样式设置。如果你想直接编写,基本结构非常简单,以内部的 dirList 函数为例:

w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprintf(w, "<pre>\n")
for _, d := range dirs {
	name := d.Name()
	if d.IsDir() {
		name += "/"
	}
	url := url.URL{Path: name}
	fmt.Fprintf(w, "<a href=\"%s\">%s</a>\n", url.String(), htmlReplacer.Replace(name))
}
fmt.Fprintf(w, "</pre>\n")
英文:

There's no redirection going on, the default file to render when requesting a directory is index.html. The directory listing is a fallback for when this file isn't found, so you can't get a directory listing without removing the index.html file.

If you want a directory listing, you'll have to write it out yourself, which you can then format and style however you choose. The basic structure is very simple if you want to write it directly, take the internal dirList function for example:

w.Header().Set(&quot;Content-Type&quot;, &quot;text/html; charset=utf-8&quot;)
fmt.Fprintf(w, &quot;&lt;pre&gt;\n&quot;)
for _, d := range dirs {
	name := d.Name()
	if d.IsDir() {
		name += &quot;/&quot;
	}
	url := url.URL{Path: name}
	fmt.Fprintf(w, &quot;&lt;a href=\&quot;%s\&quot;&gt;%s&lt;/a&gt;\n&quot;, url.String(), htmlReplacer.Replace(name))
}
fmt.Fprintf(w, &quot;&lt;/pre&gt;\n&quot;)

答案3

得分: 0

我认为有三种方法:

  1. 提交一个 PR,允许访问 /index.html 而不会重定向到 golang 的 net/http/fs 库。https://github.com/golang/go/issues/53870
  2. 修改你的代码:将 /index.html 替换为 /,以停止 301 重定向,例如:https://github.com/ahuigo/go-lib/commit/1a99191d5c01cf9025136ce8ddb9668f123de05c#diff-67e8621fbb99281a50c089bae53d4874663d3d21ca5e90809ec207c070029351R44
  3. 自定义你自己的 http fs 处理程序,而不使用官方工具。
英文:

I think there are 3 ways:

  1. Make a PR which allow accessing /index.html without redirect to golang's net/http/fs library. https://github.com/golang/go/issues/53870
  2. Hack your code: replace /index.html with / to stop 301 redirect, e.g., https://github.com/ahuigo/go-lib/commit/1a99191d5c01cf9025136ce8ddb9668f123de05c#diff-67e8621fbb99281a50c089bae53d4874663d3d21ca5e90809ec207c070029351R44
  3. Customize your own http fs handler instead of official tools.

答案4

得分: 0

假设你有一个名为"images"的目录用于存放图片,代码如下:

http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir("images"))))

但是你不想公开其中的所有文件名。正如人们所说,“沉默是金”。

在浏览器中,默认情况下,访问/images/images//images/index.html会显示该目录下的所有文件列表,这并不是你希望意外发生的事情。

我认为最简单的解决方案是通过命令行执行以下操作:

touch index.html

这将创建一个空文件,阻止自动生成的images/index.html目录列表的显示。同时,这不会阻止访问其中的任何图片。当然,黑客仍然可以尝试通过暴力猜测文件名来获取其中的文件,所以你需要保持一些常识。

英文:

Let's say you have an "images" directory for your images, like this:

http.Handle(&quot;/images/&quot;, http.StripPrefix(&quot;/images/&quot;, http.FileServer(http.Dir(&quot;images&quot;))))

But you don't want to expose all the filenames in there. As people say, "Silence is golden."

In a browser, by default, going to /images or /images/ or /images/index.html shows a listing of all the files there, which is not really something you want to do accidentally.

I think the easiest solution from the command-line:

touch index.html

This creates an empty file that blocks the auto-generated images/index.html directory listing. And this doesn't block access to any of the images in there. Of course, a hacker could still try to brute-force guess what files are in there, so you need to use some common sense.

huangapple
  • 本文由 发表于 2017年4月21日 02:22:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/43527073.html
匿名

发表评论

匿名网友

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

确定