我看到的问题是我试图将http.FileServer与 Gorilla mux Router.Handle 功能一起使用。这不起作用(图像返回 404)。myRouter := mux.NewRouter()myRouter.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir(HomeFolder + "images/"))))这有效(图像显示正常)..http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir(HomeFolder + "images/"))))下面简单的go web server程序,显示问题...package mainimport ( "fmt" "net/http" "io" "log" "github.com/gorilla/mux")const ( HomeFolder = "/root/test/")func HomeHandler(w http.ResponseWriter, req *http.Request) { io.WriteString(w, htmlContents)}func main() { myRouter := mux.NewRouter() myRouter.HandleFunc("/", HomeHandler) // // The next line, the image route handler results in // the test.png image returning a 404. // myRouter.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir(HomeFolder + "images/")))) // myRouter.Host("mydomain.com") http.Handle("/", myRouter) // This method of setting the image route handler works fine. // test.png is shown ok. http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir(HomeFolder + "images/")))) // HTTP - port 80 err := http.ListenAndServe(":80", nil) if err != nil { log.Fatal("ListenAndServe: ", err) fmt.Printf("ListenAndServe:%s\n", err.Error()) }}const htmlContents = `<!DOCTYPE HTML><html> <head> <title>Test page</title> <meta charset = "UTF-8" /> </head> <body> <p> <img src="/images/test.png" height="640" width="480"> </p> </body></html>
2 回答
Smart猫小萌
TA贡献1911条经验 获得超7个赞
截至 2015 年 5 月,gorilla/mux包仍然没有版本发布。但是现在问题不同了。不是myRouter.Handle不匹配 url 并且需要正则表达式,它确实如此!但http.FileServer需要从 url 中删除前缀。下面的例子工作正常。
ui := http.FileServer(http.Dir("ui"))
myRouter.Handle("/ui/", http.StripPrefix("/ui/", ui))
请注意,上面的示例中没有 /ui/ {rest}。您还可以包装http.FileServer到 logger gorilla/handler 中,并看到请求到 FileServer 和响应 404 出去。
ui := handlers.CombinedLoggingHandler(os.Stderr,http.FileServer(http.Dir("ui"))
myRouter.Handle("/ui/", ui) // getting 404
// works with strip: myRouter.Handle("/ui/", http.StripPrefix("/ui/", ui))
- 2 回答
- 0 关注
- 296 浏览
添加回答
举报
0/150
提交
取消