Golang Gorilla mux与http.FileServer返回404

dod*_*der 31 go gorilla

我看到的问题是我正在尝试使用http.FileServerGorilla mux Router.Handle功能.

这不起作用(图像返回404)..

myRouter := mux.NewRouter()
myRouter.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir(HomeFolder + "images/"))))
Run Code Online (Sandbox Code Playgroud)

这工作(图像显示确定)..

http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir(HomeFolder + "images/"))))
Run Code Online (Sandbox Code Playgroud)

简单的下面的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:%s\n", 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>
`
Run Code Online (Sandbox Code Playgroud)

dod*_*der 54

我在Golang-nuts讨论组上发布了这个,并 ToniCárdenas那里得到了这个解决方案 ......

标准的net/http ServeMux(使用时是您使用的标准处理程序http.Handle)和多路复用路由器有不同的匹配地址的方法.

请参阅http://golang.org/pkg/net/http/#ServeMuxhttp://godoc.org/github.com/gorilla/mux之间的差异.

所以基本上,http.Handle('/images/', ...)匹配'/ images/whatever',而myRouter.Handle('/images/', ...) 匹配'/ images /',如果你想处理'/ images/whatever',你必须......

  1. 在路由器中设置正则表达式匹配
  2. 在路由器上使用PathPrefix方法,例如:

代码示例

1.

myRouter.Handle('/images/{rest}', 
    http.StripPrefix("/images/", http.FileServer(http.Dir(HomeFolder + "images/")))
)
Run Code Online (Sandbox Code Playgroud)

2.

myRouter.PathPrefix("/images/").Handler(
    http.StripPrefix("/images/", http.FileServer(http.Dir(HomeFolder + "images/")))
)
Run Code Online (Sandbox Code Playgroud)

  • +1#2在我目前的项目中取得了成功(在我偶然发现这个答案之前.只是向读者保证#2是我正在使用和工作的). (3认同)