go - 如何设置 http.Dir(..) 相对于当前项目文件夹的目录路径
问题描述
情况
我正在使用 GoLand,有以下情况:
给出以下目录结构:
-project
--a
---website
index.html 位于 project/a/website/ 中,而 Main.go 位于 project/a/ 中,代码如下:
package main
import (
"net/http"
)
func main() {
http.Handle("/", http.FileServer(http.Dir("./website/")))
http.ListenAndServe(":99", nil)
}
如果我在 GoLand 中以 project/a/ 作为项目文件夹运行 Main.go,您可以按预期访问 localhost:99 上的网页 index.html,但如果我以 project/ 作为项目文件夹运行 Main.go,则路径为“。 /website/" inhttp.Handle("/", http.FileServer(http.Dir("./website/")))
变得错误。
问题
我必须设置什么作为目录路径http.Dir(...)
才能访问 localhost:99 上的网页,而与当前项目文件夹无关?
解决方案
使用绝对路径,然后您可以从任何地方运行您的项目。
您可能还想考虑将路径值移动到某种形式的配置中,比如在您完成项目开发并准备将其部署到服务器之后,硬编码的绝对值不一定对您有帮助,而是配置,无论是基于文件还是基于 env-var 都可以为您解决这个问题。
推荐阅读
- python - Python 通过 1 次调用设置更多属性
- spring-boot - RequestHandlerRetryAdvice 无法在 Spring Integration 中与 Ftp.outboundGateway 一起使用
- ios - 在 Mapbox iOS SDK 的标记下移动地图
- spring - 当我使用 ng build 时,proxy.conf.json 在 Angular 6 中不起作用
- android - 仅在某些活动中的操作栏?
- ruby-on-rails - 在 Rails 中添加复杂的查询
- python - 试图总结投资金额,但一直说不可迭代
- ansible - 确定演出主持人
- spring - 如何为 Spring Boot 配置服务器设置超时值
- c# - 无法从传输连接读取数据:现有连接被远程主机强行关闭