我有这样的目录结构,我使用Gorilla mux:
目录结构
twitter
layout
stylesheets
log.css
log.html
twitter.go
遵循这里的建议:http://www.shakedos.com/2014/Feb/08/serving-static-files-with-go.html我这样做了:
var router = mux.NewRouter()
func ServeStatic(router *mux.Router, staticDirectory string) {
staticPaths := map[string]string{
"styles": staticDirectory + "stylesheets",
}
for pathName, pathValue := range staticPaths {
pathPrefix := "/" + pathName + "/"
router.PathPrefix(pathPrefix).Handler(http.StripPrefix(pathPrefix,
http.FileServer(http.Dir(pathValue))))
}
}
var staticDirectory = "/layout/"
func main() {
(//other code)
ServeStatic(router, staticDirectory)
}
我仍然不能链接CSS文件。我做错了什么?
已解决
我在函数main()
中添加了这个router.PathPrefix("/").Handler(http.FileServer(http.Dir("./layout/")))
不用在main():
中添加额外的行,您可以用一种更简单的方法来实现这一点:内部ServeStatic:加上这句:"。"+ pathValue
router.PathPrefix(pathPrefix).Handler(http.StripPrefix(pathPrefix,
http.FileServer(http.Dir("."/pathValue))))
在您的Go
文件中:
func ServeStatic(router *mux.Router, staticDirectory string) {
staticPaths := map[string]string{
"styles": staticDirectory + "stylesheets",
}
for pathName, pathValue := range staticPaths {
pathPrefix := "/" + pathName + "/"
router.PathPrefix(pathPrefix).Handler(http.StripPrefix(pathPrefix,
http.FileServer(http.Dir(pathValue))))
}
// Add route prefix for stylesheets directory
router.PathPrefix("/stylesheets/").Handler(http.StripPrefix("/stylesheets/",
http.FileServer(http.Dir(staticDirectory+"stylesheets/"))))
}
然后用这个链接更新你的html
文件:
<link rel="stylesheet" type="text/css" href="/stylesheets/log.css">