【发布时间】:2019-01-06 16:02:19
【问题描述】:
我在使用 Go 制作的服务器上获取 index.html、main.js、style.css 等文件时遇到问题。
我的 html 文件在我的本地文件上与 javascript 和 css 一起工作得很好,但我不能让它在服务器上工作。
我已经尝试在我的代码中进行此操作,但它只启动 html 文件,并且 javascript、css、jquer、字体在控制台中列出,就像找不到页面(404 页面未找到)。
r := mux.NewRouter()
r.Handle("/", http.FileServer(http.Dir("./static")))
r.HandleFunc("/events", eventHandler) //Ignore this
r.NotFoundHandler = http.HandlerFunc(notFound) //This is just a custom 404.
// Create and start HTTP server.
s := &http.Server{
Handler: r,
Addr: config.Address,
}
我的问题是:
如果没有 Node.js,是否有可能做到这一点。是否有任何选项可以在 html 中显示我所有的 javascript 文件和 css。我真的不想用 Node 把这件事弄复杂。
注意
我的 html、css、javascript 代码都可以工作。我的服务器也可以,现在唯一需要做的就是将文件添加到服务器。
This is what I get
This is what I should get on server.
<html>
<head>
<link rel="stylesheet" href="main.css">
<script src="jquery-3.3.1.min.js"></script>
</head>
<body id='body'>
<div class="app-body">
<div id='left' class="left">
<div class='conferenceRoom'>Conference room
<h1 class="roomName">crane
</h1>
</div>
<div class="status">
<h1 id="free_busy" class="free_busy"></h1>
<h1 id="duration" class="duration"></h1>
</div>
</div>
</div>
<div class="right">
<div class="date" id="date"></div>
<div id='eventList' class="eventList"></div>
</div>
</div>
<script src="main.js"></script>
</body>
索引.html
这是我在名为网站的目录中的文件。服务器由以下人员启动:
go run *.go -c config.toml
这是从网站文件夹中运行的。 And this is what the files look like
【问题讨论】:
-
所以你是说所有其他文件(例如 main.js、style.css)都与 index.html 在同一个文件夹中,但你只能获取 index.html?
-
查看浏览器控制台的网络选项卡,您可能会看到资产404,这可能是由于服务器的文件夹结构和html文件资产路径不兼容造成的。
-
@DavidB 这在 Go 中非常简单,无论是本地的还是公共的,都没有关系。不需要包含 Node.js。请在服务器上添加项目文件夹结构的问题,以便我们可以看到索引文件和资产文件所在的位置。此外,您在 Go 代码中使用了相对路径,在这种情况下,请确保从服务器中的正确位置启动 go 二进制文件,以便程序的 cwd 与您的假设相同。
-
你在使用 gorilla mux 吗?如果是这样,那可能就是问题所在。您应该给出一个导入的工作示例。
-
@mkopriva 我解决了所谓的“问题”。服务器在同一个文件夹中,因此 func main 一次又一次地被重写。所以我所做的只是将一台服务器移动到另一个目录,因为它只是一个测试服务器,用于实际使用的服务器,然后从 2 个不同的终端启动服务器。再次感谢您的所有帮助。
标签: javascript html css go server