英文:
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.Router
的Path
方法,它会起作用。
r.Methods(route.Method).Name(route.Name).Handler(handler)
r.Path(route.Pattern)
而不是使用mux.Route
的Path
方法(下面有删除线的部分)。
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论