对于HTML页面中的CSS及js等静态文件,需要使用net/http包以下函数处理
StripPrefix函数
func StripPrefix(prefix string, h Handler) Handler
StripPrefix返回一个处理器,该处理器会将请求的URL.Path字段中给定前缀prefix去除后再交由h处理。StripPrefix会向URL.Path字段中没有给定前缀的请求回复404 page not found
FileServer函数
func FileServer(root FileSystem) Handler
FileServer返回一个使用FileSystem接口root提供文件访问服务的HTTP处理器。要使用操作系统的FileSystem接口实现,可使用http.Dir:
http.Handle("/", http.FileServer(http.Dir("/tmp")))
- type FileSystem
type FileSystem interface {
Open(name string) (File, error)
}
FileSystem接口实现了对一系列命名文件的访问。文件路径的分隔符为’/’,不管主机操作系统的惯例如何
- type Dir
type Dir string
Dir使用限制到指定目录树的本地文件系统实现了http.FileSystem接口。空Dir被视为".",即代表当前目录
- func (Dir) Open
func (d Dir) Open(name string) (File, error)
实例
项目的静态文件的目录结构
index.html模板文件中引入的css样式的地址
<link type="text/css" rel="stylesheet" href="static/css/style.css" >
对静态文件的处理
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("views/static/"))))
说明:
/static/会匹配以 /static/开头的路径,当浏览器请求index.html页面中的style.css文件时,static前缀会被替换为views/static,然后去 views/static/css目录下查找style.css文件
package main
import (
"html/template"
"net/http"
)
// IndexHandler 去首页
func IndexHandler(w http.ResponseWriter, r *http.Request) {
//解析模板
t := template.Must(template.ParseFiles("views/index.html"))
//执行
t.Execute(w, "")
}
func main() {
//设置处理静态资源
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("views/static/"))))
http.Handle("/pages/", http.StripPrefix("/pages/", http.FileServer(http.Dir("views/pages/"))))
http.HandleFunc("/", IndexHandler)
http.ListenAndServe(":8080", nil)
}