添加一个处理程序以处理从指定目录提供的静态文件。
例如。创建{server.go目录} / resources /并使用
http.Handle("/resources/", http.StripPrefix("/resources/", http.FileServer(http.Dir("resources"))))连同/resources/somethingsomething.css
使用StripPrefix的原因是您可以根据需要更改提供的目录,但是HTML中的引用保持不变。
例如。从/ home / www /
http.Handle("/resources/", http.StripPrefix("/resources/", http.FileServer(http.Dir("/home/www/"))))请注意,这将使资源目录列表保持打开状态。如果您想避免这种情况,请在go snippet博客上找到一个不错的摘录:
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}讨论它的原始帖子:https : //groups.google.com/forum/#!topic/golang-
nuts/bStLPdIVM6w
并使用它代替上面的行:
fs := justFilesFilesystem{http.Dir("resources/")} http.Handle("/resources/", http.StripPrefix("/resources/", http.FileServer(fs)))


