在go web服务器上使用外部CSS文件

时间:2015-09-15 07:21:51

标签: css web go

我正在尝试实现一个简单的wiki,如图所示=> 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

感谢您的帮助! 盖尔盖伊。

1 个答案:

答案 0 :(得分:5)

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

请阅读:404 page not found - Go rendering css fileWhy do I need to use http.StripPrefix to access my static files?了解详情。

另请注意,您的网页位于/edit//view/下,但HTML模板包含使用 relative 网址的CSS资源:

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

所以,例如结果将是/view/css/styles.css - 你想要的!