入口:
//静态资源
static := make(map[string]string)
static["/css"] = "assets/css"
static["/images"] = "assets/images"
static["/js"] = "assets/js"
app.Handler.SetStatic(static)
SetStatic:
func (rt *Route) SetStatic(upm map[string]string) {
for url, path := range upm {
p, err := filepath.Abs(path)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
rt.static[url] = http.FileServer(http.Dir(p))
}
}
rt.static的定义:map[string]http.Handler
;
我自定义路由实现的ServeHTTP:
var path string = r.URL.Path //当前请求地址
fmt.Println(strings.Join([]string{"handling request", path}, ":"))
//是否是静态文件
handler, isStatic := rt.isStatic(path)
if isStatic {
fmt.Println(handler)
handler.ServeHTTP(w, r)
return
}
isStatic:
func (rt *Route) isStatic(url string) (http.Handler, bool) {
var handler http.Handler
var result bool = false
for path, h := range rt.static {
if strings.Index(url, path) != 0 {
continue
}
handler = h
result = true
}
return handler,result
}
我访问http://localhost:8080/css/main.css
返回的404.
css目录我是新建了文件main.css的。
怎么搞?
你想太多了,其实这样就可以了
http.handle(“/”, http.FileServer(http.Dir(“web path”))
http.ListenAndServe(":8888”, nil)