相关疑难解决方法(0)

在 Go 中使用 http.FileServer 禁用目录列表的好方法

如果你在 Go 中使用 http.FileServer 像:

func main() {
    port := flag.String("p", "8100", "port to serve on")
    directory := flag.String("d", ".", "the directory of static file to host")
    flag.Parse()

    http.Handle("/", http.FileServer(http.Dir(*directory)))

    log.Printf("Serving %s on HTTP port: %s\n", *directory, *port)
    log.Fatal(http.ListenAndServe(":"+*port, nil))
}
Run Code Online (Sandbox Code Playgroud)

然后访问一个目录会给你一个文件列表。通常这对于 Web 服务是禁用的,而是以 404 响应,我也希望这种行为。

http.FileServer 没有此 AFAIK 的选项,我在这里看到了解决此问题的建议方法https://groups.google.com/forum/#!topic/golang-nuts/bStLPdIVM6w他们所做的是包装 http.FileSystem键入并实现自己的 Open 方法。但是,当路径是目录时,这不会给出 404,它只会给出一个空白页面,并且不清楚如何修改它以适应这一点。这就是他们所做的:

type justFilesFilesystem struct {
    fs http.FileSystem
}

func (fs justFilesFilesystem) Open(name string) (http.File, error) {
    f, err := fs.fs.Open(name)
    if err != nil { …
Run Code Online (Sandbox Code Playgroud)

http fileserver go

5
推荐指数
1
解决办法
2266
查看次数

标签 统计

fileserver ×1

go ×1

http ×1