我的简单文件服务器代码:
package main
import (
"net/http"
"os"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
func main() {
r := mux.NewRouter()
// default file handler
r.Handle("/", http.FileServer(http.Dir("web")))
// run on port 8080
if err := http.ListenAndServe(":8080", handlers.LoggingHandler(os.Stdout, r)); err != nil {
panic(err)
}
}
我的目录结构是:
cmd/server/main.go
web/index.html
web/favicon.ico
web/favicon.png
web/css/main.css
index.html
要求main.css
。因此,当我运行go run cmd/server/main.go
时,会得到以下输出:
127.0.0.1 - - [24/Dec/2019:22:45:26 -0X00] "GET / HTTP/1.1" 304 0
127.0.0.1 - - [24/Dec/2019:22:45:26 -0X00] "GET /css/main.css HTTP/1.1" 404 19
我能够看到index.html
页面,但是没有CSS。当我请求任何其他文件(例如favicon.ico
)时,我还会收到404。为什么我的FileServer
只提供index.html
服务?
答案 0 :(得分:5)
要说明为什么它不起作用,请考虑以下测试应用程序:
package main
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
)
type testHandler struct{}
func (h *testHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Printf("Got request for %s\n", r.URL)
}
func main() {
r := mux.NewRouter()
hndlr := testHandler{}
r.Handle("/", &hndlr)
// run on port 8080
if err := http.ListenAndServe(":8080", r); err != nil {
panic(err)
}
}
如果运行此命令并在浏览器中访问http://127.0.0.1:8080/
,它将记录Got request for /
。但是,如果您访问http://127.0.0.1:8080/foo
,则会收到404错误,并且不会记录任何内容。这是因为r.Handle("/", &hndlr)
仅在/
上匹配,而在其下方不匹配。
如果将其更改为r.PathPrefix("/").Handler(&hndlr)
,则它将按预期工作(路由器会将所有路径传递给处理程序)。因此,要解决您的示例,请将r.Handle("/", http.FileServer(http.Dir("web")))
更改为r.PathPrefix("/").Handler( http.FileServer(http.Dir("web")))
。
注意:因为这会将所有路径传递到FileServer
,所以实际上不需要使用Gorilla Mux;我将其保留在假设您将使用它来添加其他一些路由的位置上。