使用golang的标准库搭建网站--4.关于静态资源处理的问题
建网站不可避免的要使用各种各样的静态资源,这一节,就来看看,如何加载css,js图片等等这些资源。 在之前的基础上构造一简单的个HTML的测试文件 <HTML> <head> <title>Hello World</title> <link href="static/core.css" type="text/css" rel="stylesheet" /> </head> <body> <div id="header"> <p>this is header</p> </div> <div id="main"> <p> this is main<br /> {{.Name | showname}} </p> </div> <div id="footer"> <p>this is footer</p> </div> </body> </HTML>
再创建一个css文件: * { font-size: 30px; font-weight: bold; }
#header { background-color: red }
#main { background-color: yellow; }
#footer { background-color: blue; }
然后运行之前的go文件,结果如下: 从运行结果来看,会发现css并没有起作用,我们来看一看为什么会这样: http.HandleFunc("/",Index)
我们期望的是当直接访问 http://localhost:8080 时就能转到index.html 问题出在哪里呢? func ListenAndServe(addr string,handler Handler) error
如果要自己写路由函数的话,就得先实现Handler这个接口,声明如下: type Handler interface { ServeHTTP(ResponseWriter,*Request) }
先声明一个结构体: type MyMux struct { routers map[string]func(http.ResponseWriter,*http.Request) }
实现ServeHTTP方法: func (p *MyMux) ServeHTTP(w http.ResponseWriter,r *http.Request) {
//遍历routers,寻找匹配的path
for path,f := range p.routers {
if r.URL.Path == path {
f(w,r)
return
}
}
fmt.Fprintf(w,"Error: Don't match URL '%s'",r.URL.Path)
}
重写main函数: func main() {
mux := &MyMux{}
mux.routers = make(map[string]func(http.ResponseWriter,*http.Request))
mux.routers["/"] = Index
err := http.ListenAndServe(":8080",mux)
if err != nil {
fmt.Println("Error: ",err)
}
}
这样的话对于每一次的请求,都遍历一次mux.routers,来查找是否有匹配到的路由, 我们需要重新实现ServeHTTP方法,但也只需要修改if的判断条件即可: if ok,_ :=regexp.MatchString("^" + path + "$",r.URL.Path); ok { f(w,r) return }
并且新增一条是用正则表达式的路由: mux.routers["/static/.+"] = Static
接下来,我们就要针对匹配到的static文件中的文件做单独的处理 func Static(w http.ResponseWriter,r *http.Request) {
fmt.Println("Deal Static: ",r.URL.Path)
w.Header().Set("Content-Type","text/css")
http.ServeFile(w,r,"." + r.URL.Path)
}
现在再通过浏览器分别访问一下URL: 当我们访问 http://localhost:8080/ 的时候,浏览器会向服务器发送一个GET /static/core.css 此时,当我们访问 http://localhost:8080/ 的时候,就会发现页面解析正常了,效果如下: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |