找不到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.

In src folder contains css/somefilename.css, src also contains server/server.go.

The code inside my server.go file is as follows.

http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("css"))))

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

the html code is as follows:

<link rel="stylesheet" type="text/css" href="../css/css490.css" />
douyeke2695
douyeke2695 仅出于测试目的,用filepath.FromSlash(path.Clean(“css”)替换“css”会更好(对于任何平台)吗?
5 年多之前 回复
dousi4257
dousi4257 是的,当我使用完整路径时,它可以按预期工作。我唯一的困扰是为什么它可以在上面的代码在我的朋友机器(mac)上运行,但是当我在我的机器(windows)上运行它时却不起作用。实际上,css文件到server.go的文件路径相同
5 年多之前 回复
dousui8263
dousui8263 如果将css文件夹的完整路径放在http.FileServer(http.Dir(“/full/path/of/css”))中,这样做会更好吗?
5 年多之前 回复

1个回答



由于您没有为 css </ code>文件夹指定完整路径,因此无论您的CSS文件是 找到的位置取决于您从中运行应用程序的文件夹</ em>(工作目录,这是解析到的相对路径)。</ p>

例如,如果您启动 从您的 src </ code>和 go一起运行server / server.go </ code>的应用程序,它将起作用。 如果使用 go run server.go </ code>从 src / server </ code>文件夹中启动它,则它将不起作用。 另外,如果您从应用程序中创建一个本机可执行文件,并将其放入 bin </ code>文件夹中,然后从 bin </ code>文件夹中启动该可执行文件,则由于 > css </ code>文件夹不在 bin </ code>文件夹中。</ p>

可以通过开始运行go server / server.go </ code> 从 src </ code>文件夹中,或将 css </ code>文件夹复制到您的 bin </ code>文件夹中,然后从 bin </ code>文件夹启动可执行文件 并且它应该可以工作(但在这种情况下,您还必须复制其他静态文件,例如html模板)。</ p>
</ div>

展开原文

原文

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).

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.

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).

dongmi1872
dongmi1872 谢谢你的解释。 我以为我正在从src / server运行我的文件,但是我正在使用命令go install server,它会在bin文件夹中创建一个可执行文件。
5 年多之前 回复
dpn68721
dpn68721 这似乎无休止地吸引了很多人。
5 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐