【发布时间】:2018-12-12 15:49:21
【问题描述】:
当我实现一个静态服务器处理程序时,如果我访问根路径,它将显示整个目录,如下所示:
我的代码是:
package main
import (
"flag"
"log"
"net/http"
"strings"
)
func main() {
port := flag.String("p", "3000", "port to serve on")
directory := flag.String("d", ".", "the directory of static file to host")
flag.Parse()
http.Handle("/statics/", http.StripPrefix(strings.TrimRight("/statics/", "/"), http.FileServer(http.Dir(*directory))))
log.Printf("Serving %s on HTTP port: %s\n", *directory, *port)
log.Fatal(http.ListenAndServe(":"+*port, nil))
}
【问题讨论】:
-
也许这就是您要找的东西?然而,由此产生的答案对我来说有点肮脏。它基本上只包括检查当前请求的资源是目录还是文件并相应地处理它。 stackoverflow.com/questions/49589685/…
-
呃,是的,这就是
Dir所做的:A Dir implements FileSystem using the native file system restricted to a specific directory tree 到底是什么问题? -
@RickyA 问题是大多数其他服务器在访问目录时默认返回 404,这是一个非常明智的安全默认设置。 Go 没有提供关闭它的方法。基本上,问题的答案归结为
Dir文档的最后一段:“创建自定义文件系统实现。” -
@RayfenWindspear 这是一个假设。也许 OP 期望一个 index.html 被渲染,所以我想从 OP 那里听到它。
-
@RickyA 不要显得粗鲁,但这似乎是一个安全的假设。使用 css、js 等提供“静态”目录通常不会在目录的
statics/级别有 index.html,因为它只是单独类型静态的容器。但是,是的,尽管如此,一个假设......
标签: http go static-files