Golang Gorilla mux with http.FileServer returning 404



我看到的问题是我正在尝试将 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服务器程序,显示问题...

package main
import (
    "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:%sn", err.Error())
    }
}
const htmlContents = `<!DOCTYPE HTML>
<html lang="en">
  <head>
    <title>Test page</title>
    <meta charset = "UTF-8" />
  </head>
  <body>
    <p align="center">
        <img src="/images/test.png" height="640" width="480">
    </p>
  </body>
</html>
`

我将其发布在Golang-Nuts讨论组上,并从ToniCárdenas获得了此解决方案...

标准的NET/HTTP ServeMux(使用http.Handle时,您正在使用的标准处理程序)和MUX路由器具有匹配地址的不同方式。

请参阅http://golang.org/pkg/net/http/#servemux和http://godoc.org/github.com/gorilla/gorilla/mux.

基本上, http.Handle('/images/', ...)匹配"/images/erthing',而 myRouter.Handle('/images/', ...) 唯一匹配'/images/',如果您想处理'/images/whthing',则必须..。

选项1 - 在路由器中使用正则表达式匹配

myRouter.Handle("/images/{rest}",
     http.StripPrefix("/images/", http.FileServer(http.Dir(HomeFolder + "images/"))))

选项2 - 使用路由器上的PathPrefix方法:

myRouter.PathPrefix("/images/").Handler(http.StripPrefix("/images/", 
     http.FileServer(http.Dir(HomeFolder + "images/"))))

截至2015年5月,大猩猩/mux软件包仍然没有版本。但是问题现在有所不同。并不是说myRouter.Handle与URL不匹配,并且需要Regexp,它确实如此!但是http.FileServer需要从URL中删除前缀。下面的示例正常工作。

ui := http.FileServer(http.Dir("ui"))
myRouter.Handle("/ui/", http.StripPrefix("/ui/", ui))

注意,在abowe示例中没有/ui/ {reth} 。您也可以将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))

最新更新