我按照this教程编写了一个非常基本的Web应用程序.我想在外部样式表中添加CSS规则,但它不起作用-当呈现HTML模板时,出现问题,CSS被完全忽略.如果我将规则放在标签中,它会起作用,但我不想处理这个问题.
在Go Web应用程序中,如何呈现外部CSS样式表?
我按照this教程编写了一个非常基本的Web应用程序.我想在外部样式表中添加CSS规则,但它不起作用-当呈现HTML模板时,出现问题,CSS被完全忽略.如果我将规则放在标签中,它会起作用,但我不想处理这个问题.
在Go Web应用程序中,如何呈现外部CSS样式表?
添加处理程序以处理指定目录中的静电文件.
例如.创建{server.go目录}/resources/并使用
http.Handle("/resources/", http.StripPrefix("/resources/", http.FileServer(http.Dir("resources"))))
与/resources/omethingomething.css一起使用
使用StripPrefix的原因是,您可以随意更改服务目录,但HTML中的引用保持不变.
在家里服务/
http.Handle("/resources/", http.StripPrefix("/resources/", http.FileServer(http.Dir("/home/www/"))))
请注意,这将使资源目录列表保持打开状态. 如果你想防止这种情况,在Go Snippet博客上有一个很好的片段:
http://gosnip.posterous.com/disable-directory-listing-with-httpfileserver个
Edit:Posterous现在不见了,所以我只是把代码从Golang邮件列表中拿出来,然后把它寄到这里.
type justFilesFilesystem struct {
fs http.FileSystem
}
func (fs justFilesFilesystem) Open(name string) (http.File, error) {
f, err := fs.fs.Open(name)
if err != nil {
return nil, err
}
return neuteredReaddirFile{f}, nil
}
type neuteredReaddirFile struct {
http.File
}
func (f neuteredReaddirFile) Readdir(count int) ([]os.FileInfo, error) {
return nil, nil
}
讨论它的原始帖子:https://groups.google.com/forum/#!topic/golang-nuts/bStLPdIVM6w
并像这样使用它来代替上面的行:
fs := justFilesFilesystem{http.Dir("resources/")}
http.Handle("/resources/", http.StripPrefix("/resources/", http.FileServer(fs)))