【发布时间】:2020-06-30 18:49:59
【问题描述】:
在构建一个简单的 API 时,我在使用 Go 和 gorilla/mux 路由器时遇到了以下问题。我确定这是我脸上常见的愚蠢错误,但我看不到。
简化项目结构
|--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()
// ...
}
子路由工作正常,中间件和所有。如果我转到localhost:5000/static/img1.png,img 下的图像将正确提供。
问题是,去localhost:5000 服务于驻留在public 中的index.html,但随后localhost:5000/image.png 是404 not found。
这里发生了什么?
【问题讨论】: