Lin*_*son 25 html css web-applications go
我按照本教程编写了一个非常基本的Web应用程序.我想在外部样式表中添加css规则,但它不起作用 - 当呈现HTML模板时,出现问题并完全忽略CSS.如果我将规则放在标签中,它可以工作,但我不想处理它.
在Go Web应用程序中,如何呈现外部CSS样式表?
min*_*omi 35
添加处理程序以处理来自指定目录的服务静态文件.
例如.创建{server.go目录}/resources /并使用
http.Handle("/resources/", http.StripPrefix("/resources/", http.FileServer(http.Dir("resources"))))
Run Code Online (Sandbox Code Playgroud)
以及/resources/somethingsomething.css
使用StripPrefix的原因是您可以根据需要更改服务目录,但保持HTML中的引用相同.
例如.从/ home/www /服务
http.Handle("/resources/", http.StripPrefix("/resources/", http.FileServer(http.Dir("/home/www/"))))
Run Code Online (Sandbox Code Playgroud)
请注意,这将使资源目录列表保持打开状态.如果你想阻止它,那么go go片段博客上有一个很好的片段:
http://gosnip.posterous.com/disable-directory-listing-with-httpfileserver
编辑: 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
}
Run Code Online (Sandbox Code Playgroud)
讨论它的原帖:https://groups.google.com/forum/#!topic/golang -nuts/bStLPdIVM6w
并使用它代替上面的行:
fs := justFilesFilesystem{http.Dir("resources/")}
http.Handle("/resources/", http.StripPrefix("/resources/", http.FileServer(fs)))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11622 次 |
最近记录: |