在Go Web服务器上使用外部CSS文件

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

Using external CSS file on a go web server

问题

我正在尝试实现一个简单的维基百科,参考链接如下:
https://golang.org/doc/articles/wiki/

我知道这个问题已经被问过很多次了,但是我无法让静态内容在我的代码中加载。很愚蠢,我按照说明添加了处理静态内容的处理程序,但是CSS仍然没有在HTML文件中使用。

我像这样添加了处理程序:

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

完整的代码可以在我的GitHub页面上看到:
https://github.com/Skarlso/goprojects/tree/master/golangwiki

谢谢帮助!
Gergely.

英文:

I'm trying to implement a simple wiki as depicted here =>
https://golang.org/doc/articles/wiki/

I know this has been asked several times, but I can't get the static content to load in my code. It's stupid, I followed the instructions which let's me add a handler for static content but the CSS still does not get used in the html file.

I added the handlers like this:

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

The whole code can be seen here, on my github page => https://github.com/Skarlso/goprojects/tree/master/golangwiki

Thanks for the help!
Gergely.

答案1

得分: 5

由于您使用的是相对路径(例如http.Dir("tmp/css")),因此从哪个文件夹开始启动应用程序非常重要。

请阅读以下内容以获取更多详细信息:404页面未找到-Go渲染CSS文件为什么需要使用http.StripPrefix来访问静态文件?

还请注意,您的页面可以在/edit//view/下访问,但HTML模板使用相对URL包含CSS资源:

<link rel="stylesheet" href="css/styles.css">

因此,例如,结果将是/view/css/styles.css - 这不是您想要的!

英文:

Since you use relative paths (e.g. http.Dir(&quot;tmp/css&quot;), it is important how (from which folder) you start your app.

Please read: 404 page not found - Go rendering css file and Why do I need to use http.StripPrefix to access my static files? for more details.

Also note that your pages are available under /edit/ and /view/, but the HTML templates include CSS resources using relative urls:

&lt;link rel=&quot;stylesheet&quot; href=&quot;css/styles.css&quot;&gt;

So e.g. the result will be /view/css/styles.css - not what you want!

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

发表评论

匿名网友

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

确定