【问题标题】:serving static files in different locations在不同位置提供静态文件
【发布时间】:2016-10-25 02:16:51
【问题描述】:

我正在编写一个 Go 应用程序,它为两个不同目录中的文件提供服务。

我的项目结构:

PROJECT_DIR
PROJECT_DIR/config
PROJECT_DIR/src
PROJECT_DIR/client
PROJECT_DIR/client/node_modules
PROJECT_DIR/client/www

在我的主 go 文件中,我使用以下代码启动文件服务器:

func main() {
log.Print("started web server...");
httpsPortStr := ":" + strconv.FormatUint(config.CfgIni.HttpsPort, 10)
log.Printf("starting https web server at port %v", config.CfgIni.HttpsPort)
http.Handle("/", http.FileServer(http.Dir("client/www")))
http.Handle("/node_modules",http.FileServer(http.Dir(("client/node_modules"))))
err := http.ListenAndServeTLS(httpsPortStr, config.CfgIni.CertificateFile, config.CfgIni.PrivateKeyFile, nil)
if err != nil {
    log.Fatalf("https server stopped with the following error: %v", err)
} else {
    log.Print("https server stopped with no error")
}
}

如您所见,我将 / 映射到 client/www 并将 /node_modules 映射到 client/node_modules。

当我尝试访问客户端/www 上的文件时,例如 https://host:port/test.html,效果很好!

当我尝试访问 client/node_modules 上的文件时,例如:https://host:port/node_modules/test.html,我得到 404 page not found。

test.html 文件存在于这两个位置并且是可读的(没有权限问题)。

我可能以某种方式配置了错误的路由。

有什么想法吗?

谢谢!

【问题讨论】:

    标签: http go


    【解决方案1】:

    FileServer 正在尝试将 /node_modules/... 等路径路由到文件“client/node_modules/node_modules/...”

    所以使用StripPrefix,例如:

    http.Handle("/node_modules", http.StripPrefix("/node_modules", http.FileServer(http.Dir(("client/node_modules")))))
    

    在此处查看另一个answer

    【讨论】:

    • 谢谢。我需要向 http.Handle 提供第一个参数,以下值:“/node_modules/”(目录的结尾 /)。现在可以了
    猜你喜欢
    • 2014-01-26
    • 2023-04-11
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    • 1970-01-01
    • 2012-06-15
    • 1970-01-01
    相关资源
    最近更新 更多