猿问

在不同位置提供静态文件

我正在编写一个在两个不同目录中提供文件的 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")

}

}

如您所见,我映射/到客户端/www 和/node_modules客户端/node_modules。


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


当我尝试访问 client/node_modules 上的文件时,例如:https://host:port/node_modules/test.html,我找不到 404 页面。


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


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


有任何想法吗?


慕虎7371278
浏览 187回答 1
1回答

PIPIONE

FileServer 正在尝试将 /node_modules/... 等路径路由到文件“client/node_modules/node_modules/...”所以使用StripPrefix,例如:http.Handle("/node_modules", http.StripPrefix("/node_modules", http.FileServer(http.Dir(("client/node_modules")))))在此处查看另一个答案。
随时随地看视频慕课网APP

相关分类

Go
我要回答