首页 > 解决方案 > 如何设置 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 上的网页,而与当前项目文件夹无关?

标签: godirectorypath

解决方案


使用绝对路径,然后您可以从任何地方运行您的项目。

您可能还想考虑将路径值移动到某种形式的配置中,比如在您完成项目开发并准备将其部署到服务器之后,硬编码的绝对值不一定对您有帮助,而是配置,无论是基于文件还是基于 env-var 都可以为您解决这个问题。


推荐阅读