加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang大猩猩mux与http.FileServer返回404

发布时间:2020-12-16 19:19:59 所属栏目:大数据 来源:网络整理
导读:我看到的问题是我正在尝试使用http.FileServer与Gorilla mux Router.Handle函数。 这不起作用(图像返回404).. myRouter := mux.NewRouter()myRouter.Handle("/images/",http.StripPrefix("/images/",http.FileServer(http.Dir(HomeFolder + "images/")))) 这
我看到的问题是我正在尝试使用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.FileServer(http.Dir(HomeFolder + "images/"))))

简单的下载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.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.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>
`
我发贴在加龙人讨论组,得到了 this solution from Toni Cárdenas …

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

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

所以基本上,http.Handle(‘/ images /’,…)匹配’/ images / whatever’,而myRouter.Handle(‘/ images /’,…)只匹配’/ images /’,如果你想要处理’/图像/任何’,你必须…

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

代码示例

1。

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

2。

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读