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。
这里发生了什么?
慕尼黑5688855
相关分类