404页面未找到 – 进行渲染css文件

huangapple go评论101阅读模式
英文:

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.csssrc还包含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(&quot;/css/&quot;, http.StripPrefix(&quot;/css/&quot;, http.FileServer(http.Dir(&quot;css&quot;))))

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:

&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;../css/css490.css&quot; /&gt;

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

huangapple
  • 本文由 发表于 2015年2月3日 15:25:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/28293452.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定