英文:
404 page not found - Go rendering css file
问题
我目前正在使用Go语言进行工作。我在本地机器上创建了一个Web服务器。我按照这个页面上的说明进行操作https://stackoverflow.com/questions/13302020/rendering-css-in-a-go-web-application,但是我仍然遇到404错误,程序似乎无法找到我的CSS文件所在的位置。我的目录结构如下。
在src
文件夹中包含css/somefilename.css
,src
还包含server/server.go
。
我server.go
文件中的代码如下。
http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("css"))))
当我访问localhost:8080/css/
时,我得到404页面未找到的错误。我还使用模板来渲染HTML代码。模板位于以下文件夹中
src/templates/layout.html
HTML代码如下:
<link rel="stylesheet" type="text/css" href="../css/css490.css" />
英文:
I'm currently working in Go. I created a web server on my local machine. I followed the instruction on this page https://stackoverflow.com/questions/13302020/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" />
答案1
得分: 3
由于您没有为css
文件夹指定完整路径,而只是相对路径,所以您的css文件是否被找到取决于您运行应用程序的文件夹(即工作目录,相对路径会解析到这里)。
例如,如果您从src
文件夹中使用go run server/server.go
启动应用程序,它将正常工作。如果您从src/server
文件夹中使用go run server.go
启动它,它将无法工作。另外,如果您从bin
文件夹中启动将应用程序创建为本机可执行文件,并且您从bin
文件夹中启动它,这也不会起作用,因为css
文件夹不在bin
文件夹中。
要么从src
文件夹中使用go run server/server.go
启动它,要么将css
文件夹复制到bin
文件夹中,并从bin
文件夹中启动可执行文件,它应该可以工作(但在这种情况下,您还必须复制其他静态文件,如HTML模板)。
英文:
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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论