英文:
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("tmp/css")
, 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:
<link rel="stylesheet" href="css/styles.css">
So e.g. the result will be /view/css/styles.css
- not what you want!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论