第二个 FileServer 提供 html 但不提供图像

gorilla/mux在构建简单的 API 时,我遇到了 Go 和路由器的以下问题。我确信这是我脸上常见的愚蠢错误,但我看不到它。


简化的项目结构

|--main.go

|

|--public/--index.html

|        |--image.png

|

|--img/--img1.jpg

|     |--img2.jpg

|     |--...

|...

main.go

package main


import (

    "net/http"

    "github.com/gorilla/mux"

)


var Router = mux.NewRouter()


func InitRouter() {

    customers := Router.PathPrefix("/customers").Subrouter()


    customers.HandleFunc("/all", getAllCustomers).Methods("GET")

    customers.HandleFunc("/{customerId}", getCustomer).Methods("GET")

    // ...

    // Registering whatever middleware

    customers.Use(middlewareFunc)


    users := Router.PathPrefix("/users").Subrouter()


    users.HandleFunc("/register", registerUser).Methods("POST")

    users.HandleFunc("/login", loginUser).Methods("POST")

    // ...


    // Static files (customer pictures)

    var dir string

    flag.StringVar(&dir, "images", "./img/", "Directory to serve the images")

    Router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir))))


    var publicDir string

    flag.StringVar(&publicDir, "public", "./public/", "Directory to serve the homepage")

    Router.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir(publicDir))))

}


func main() {

    InitRouter()

    // Other omitted configuration

    server := &http.Server{

        Handler: Router,

        Addr:    ":" + port,

        // Adding timeouts

        WriteTimeout: 15 * time.Second,

        ReadTimeout:  15 * time.Second,

    }


    err := server.ListenAndServe()

    // ...

}

子路由工作正常,中间件和所有。img如果我去下面的图像是正确的localhost:5000/static/img1.png。


问题是,将localhost:5000服务于index.html驻留的public,但随后localhost:5000/image.png是 a 404 not found。


这里发生了什么?


红颜莎娜
浏览 86回答 1
1回答

慕尼黑5688855

更改此行:// handles '/' and *ONLY* '/'Router.Handle("/",        http.StripPrefix("/", http.FileServer(http.Dir(publicDir))))对此:// handles '/' and all sub-routesRouter.PathPrefix("/").Handler(        http.StripPrefix("/",http.FileServer(http.Dir(publicPath))))基本上,在您的原始代码中,路由器/正在处理此路径并且仅处理该路径(无子路由)。您可能想知道为什么您的原始代码至少对一个文件“有效”(index.html)。原因是http.FileServer给定的路径是目录 - 而不是文件 - 将默认为索引页面文件提供服务index.html(请参阅FileServer 源代码)。UsingPathPrefix允许 (fileserver) 处理程序接受path 下的所有URL 路径/。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go