本文介绍了Golang Gorilla mux与http.FileServer返回404的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到的问题是我试图在Gorilla mux Router.Handle函数中使用 http.FileServer



这不起作用(图像返回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 /)))

下面简单介绍一下web服务器程序,显示问题...

 包主
$ b $导入(
fmt
净/ http
io
log
github.com/gorilla/mux


const(
HomeFolder =/ root / test /


func HomeHandler(w http.ResponseWriter,req * http.Request){
io.WriteString(w,htmlConte nts)
}

func main(){

myRouter:= mux.NewRouter()
myRouter.HandleFunc(/,HomeHandler)
//
//下一行,图像路由处理程序的结果是
// test.png图像返回404.
// myRouter.Handle(/ images /,http.StripPrefix(/ images /,http.FileServer(http.Dir(HomeFolder +images /))))
//
myRouter.Host(mydomain.com )
http.Handle(/,myRouter)

//这种设置图像路由处理函数的方法工作正常。
// test.png显示正常。
http.Handle(/ images /,http.StripPrefix(/ images /,http.FileServer(http.Dir(HomeFolder +images /))))

// HTTP - 端口80
err:= http.ListenAndServe(:80,nil)

如果err!= nil {
log.Fatal(ListenAndServe: ,err)
fmt.Printf(ListenAndServe:%s\\\
,err.Error())
}
}

const htmlContents =`< ;!DOCTYPE HTML>
< html lang =en>
< head>
< title>测试页面< /标题>
< meta charset =UTF-8/>
< / head>
< body>
< p align =center>
< img src =/ images / test.pngheight =640width =480>
< / p>
< / body>
< / html>
`


解决方案

在golang-nuts讨论组上获得并获得 ...



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



查看和。



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


  1. 在您的路由器中设置正则表达式匹配,或者在您的路由器上使用PathPrefix方法,如


  2. 代码示例



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





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


    The problem I'm seeing is that I'm trying to use the http.FileServer with the Gorilla mux Router.Handle function.

    This doesn't work (the image returns a 404)..

    myRouter := mux.NewRouter()
    myRouter.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir(HomeFolder + "images/"))))
    

    this works (the image is shown ok)..

    http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir(HomeFolder + "images/"))))
    

    Simple go web server program below, showing the problem...

    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>
    `
    
    解决方案

    I posted this on golang-nuts discussion group and got this solution from Toni Cárdenas ...

    The standard net/http ServeMux (which is the standard handler you are using when you use http.Handle) and the mux Router have different ways of matching an address.

    See the differences between http://golang.org/pkg/net/http/#ServeMux and http://godoc.org/github.com/gorilla/mux.

    So basically, http.Handle('/images/', ...) matches '/images/whatever', while myRouter.Handle('/images/', ...) only matches '/images/', and if you want to handle '/images/whatever', you have to ...

    1. set a regular expression match in your router or
    2. use the PathPrefix method on your router, like:

    Code examples

    1.

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

    2.

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

    这篇关于Golang Gorilla mux与http.FileServer返回404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 06:55