36

我看到的问题是我正在尝试使用http.FileServerGorilla 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 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>
`
4

2 回答 2

66

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

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

查看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 - 在路由器中使用正则表达式匹配

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/"))))
于 2014-01-21T07:20:20.493 回答
0

截至 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))
于 2015-05-01T20:25:32.817 回答