2015-05-05 35 views
2

我最近问到有关服务静态内容和处理404与大猩猩多路复用器;用手柄代替PathPrefix时,应用程序可以服务于根页面(http://localhost:8888):服务静态内容和处理404与大猩猩工具包找不到

func main() { 
    r := mux.NewRouter() 
    r.HandleFunc("/myService", ServiceHandler) 
    r.Handle("/", http.FileServer(http.Dir("./static"))) 
    r.NotFoundHandler = http.HandlerFunc(notFound) 
    l, _ := net.Listen("tcp", "8888") 
    http.Serve(l, r) 
} 

然而根页面(例如http://localhost:8888/demo/page1.html)内页面的请求由404处理器得到拦截。有什么办法可以防止这种情况发生,同时捕获不存在的页面或服务的请求?这是目录结构:

... 
main.go 
static\ 
    | index.html 
    demo\ 
    page1.html 
    demo.js 
    demo.css 
    | jquery\ 
     | <js files> 
    | images\ 
     | <png files> 

前一题:

我现在用的是大猩猩MUX工具来处理在Web服务器应用程序的http请求:

func main() { 
    r := mux.NewRouter() 
    r.HandleFunc("/myService", ServiceHandler) 
    r.PathPrefix("/").Handler(http.FileServer(http.Dir("./static"))) 
    l, _ := net.Listen("tcp", "8888") 
    http.Serve(l, r) 
} 

我想添加一个处理程序对于无效的URLS,但它永远不会被调用:

func main() { 
    r := mux.NewRouter() 
    r.HandleFunc("/myService", ServiceHandler) 
    r.NotFoundHandler = http.HandlerFunc(notFound) 
    r.PathPrefix("/").Handler(http.FileServer(http.Dir("static"))) 
    l, _ := net.Listen("tcp", "8888") 
    http.Serve(l, r) 
} 

如果我删除了静态处理程序, d处理程序被调用。但是,应用程序需要从非绝对路径提供静态内容。有没有办法将404与处理结合起来?

+0

你的目录结构是什么? – MIkCode

+0

加入问题 –

回答

1

我怀疑r.PathPrefix("/").Handler()会匹配任何路径,使得notfound处理程序无用。

正如在 “route.go ”中提到:

// Note that it does not treat slashes specially 
// ("`/foobar/`" will be matched by the prefix "`/foo`") 
// so you may want to use a trailing slash here. 

如果您正在使用PathPrefix(如those tests),用它为特定路径,而不是一般的“ /”。

+0

谢谢冯,我也怀疑过。我们要为根index.html页面提供服务,因此在浏览器中输入“http:// localhost:8888”会为用户提供静态内容。因此r.PathPrefix(“/”)。Handler()。是否有替代“/”,允许404处理和提供静态内容? –

+0

@CloomMagoo是的,但副作用是'NotFoundHandler'永远不会被调用。 – VonC

+0

@CloomMagoo for“/”,使用'mux.HandleFunc(“/”,...)'而不是'PathPrefix' – VonC