找不到 404 页面 - 去渲染 css 文件 [英] 404 page not found - Go rendering css file
问题描述
我目前正在使用 Go.我在本地机器上创建了一个 Web 服务器.我按照此页面上的说明在 Go Web 应用程序中渲染 CSS但我仍然收到 404 错误,即程序似乎无法找到我的 css 文件所在的位置.我的目录如下.
I'm currently working in Go. I created a web server on my local machine. I followed the instruction on this page Rendering CSS in a Go Web Application but I'm still getting the 404 error that the program can't seem to find where my css file is. My directory is as follows.
src
文件夹包含 css/somefilename.css
,src
也包含 server/server.go
.
In src
folder contains css/somefilename.css
, src
also contains server/server.go
.
我的 server.go
文件中的代码如下.
The code inside my server.go
file is as follows.
http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("css"))))
当我转到 localhost:8080/css/
时,我发现 404 页面未找到.我还使用模板来呈现 html 代码.模板在文件夹中
When I go to localhost:8080/css/
I get 404 page not found. I'm also using templates to render the html code. The templates are in the folder
src/templates/layout.html
html代码如下:
<link rel="stylesheet" type="text/css" href="../css/css490.css" />
推荐答案
由于你没有为 css
文件夹指定完整路径,只是一个相对的,你的 css 文件是否被找到取决于运行应用程序的文件夹(工作目录,这是解析到的相对路径).
Since you don't specify full path for the css
folder just a relative one, whether your css files are found depends on the folder you run your application from (the working directory, this is what relative paths are resolved to).
例如,如果您使用 go run server/server.go
从 src
启动您的应用程序,它将起作用.如果您从 src/server
文件夹使用 go run server.go
启动它,它将无法工作.此外,如果您从应用程序创建一个本机可执行文件并将其放入 bin
文件夹并从 bin
文件夹开始,这也将不起作用,因为 >css
文件夹不在 bin
文件夹中.
For example if you start your application from your src
with go run server/server.go
it will work. If you start it from your src/server
folder with go run server.go
, it will not work. Also if you create a native executable from your app which is put into the bin
folder and you start that from the bin
folder, this also won't work because the css
folder is not in the bin
folder.
要么用 go run server/server.go
从 src
文件夹开始,要么将 css
文件夹复制到你的 bin
文件夹并从 bin
文件夹启动可执行文件,它应该可以工作(但在这种情况下,您还必须复制其他静态文件,如 html 模板).
Either start it with go run server/server.go
from the src
folder, or copy the css
folder to your bin
folder and start the executable from the bin
folder and it should work (but in this case you also have to copy other static files like html templates).
这篇关于找不到 404 页面 - 去渲染 css 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!