调用http.FileServer在http.HandlerFunc中。

huangapple go评论80阅读模式
英文:

Calling http.FileServer in an http.HandlerFunc

问题

最近我遇到了一些问题...这是我的代码:

https://gist.github.com/anonymous/af1e6d922ce22597099521a4b2cfa16f

我的问题是:我试图从文件夹./docs/html中提供一些HTML文件。我的文件夹结构如下:

.
├── docs
│   └── html
│       ├── index.html
│       └── rest.html
└── main.go

你会注意到在这个代码片段中,我在http.HandlerFunc ServeDocs上调用了ServeHTTP方法,然后通过一个路由器(mux.Router)进行处理。我遇到的问题是,出于某种原因,只有index.html文件在localhost:8080/上被提供,当我导航到localhost:8080/rest.html时,会得到一个404错误。

真奇怪的是,当我删除所有的路由器代码,然后像下面这样做时:

fs := http.FileServer(http.Dir("./docs/html"))
http.Handle("/", fs)

log.Println("Listening...")
http.ListenAndServe(":3000", nil)

一切都正常工作。有人知道发生了什么吗?我已经花了几个小时试图解决这个问题,但最终放弃了。

英文:

so I've had some trouble with this lately... Here is my code:

https://gist.github.com/anonymous/af1e6d922ce22597099521a4b2cfa16f

My problem: I'm trying to serve up some HTML files from a folder: ./docs/html. My folder structure:

.
├── docs
│   └── html
│       ├── index.html
│       └── rest.html
└── main.go

You'll notice in the gist I am calling the ServeHTTP method on the http.HandlerFunc ServeDocs, which is then going through a router (mux.Router). The problem I'm having is for some reason the only file being served up at localhost:8080/ is index.html, and when I navigate to localhost:8080/rest.html I get a 404.

The really odd part is that when I remove all the router code and do something like the following:

fs := http.FileServer(http.Dir("./docs/html"))
http.Handle("/", fs)

log.Println("Listening...")
http.ListenAndServe(":3000", nil)

Everything works as it should. Anybody know what's going on? I've spent hours trying to figure this out and I've finally given up.

答案1

得分: 1

如果你使用mux.RouterPath方法,它会起作用。

r.Methods(route.Method).Name(route.Name).Handler(handler)
r.Path(route.Pattern)

而不是使用mux.RoutePath方法(下面有删除线的部分)。

r.Methods(route.Method).Path(route.Pattern).Name(route.Name).Handler(handler)

我对gorilla/mux不太熟悉,所以无法找到确切的原因。

英文:

It works if you use mux.Router's Path method

> r.Methods(route.Method).Name(route.Name).Handler(handler)
> r.Path(route.Pattern)

instead of mux.Route's Path method (strikethrough'd below)

> r.Methods(route.Method)<s>.Path(route.Pattern)</s>.Name(route.Name).Handler(handler)

I am not much familiar with gorilla/mux so couldn't find exact reason behind this.

huangapple
  • 本文由 发表于 2017年1月21日 08:44:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/41774588.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定