gorilla/mux在構建簡單的 API 時,我遇到了 Go 和路由器的以下問題。我確信這是我臉上常見的愚蠢錯誤,但我看不到它。簡化的項目結構|--main.go||--public/--index.html| |--image.png||--img/--img1.jpg| |--img2.jpg| |--...|...main.gopackage mainimport ( "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。這里發生了什么?
1 回答

慕尼黑5688855
TA貢獻1848條經驗 獲得超2個贊
更改此行:
// handles '/' and *ONLY* '/'
Router.Handle("/",
http.StripPrefix("/", http.FileServer(http.Dir(publicDir))))
對此:
// handles '/' and all sub-routes
Router.PathPrefix("/").Handler(
http.StripPrefix("/",http.FileServer(http.Dir(publicPath))))
基本上,在您的原始代碼中,路由器/正在處理此路徑并且僅處理該路徑(無子路由)。
您可能想知道為什么您的原始代碼至少對一個文件“有效”(index.html)。原因是http.FileServer給定的路徑是目錄 - 而不是文件 - 將默認為索引頁面文件提供服務index.html(請參閱FileServer 源代碼)。
UsingPathPrefix允許 (fileserver) 處理程序接受path 下的所有URL 路徑/。
- 1 回答
- 0 關注
- 104 瀏覽
添加回答
舉報
0/150
提交
取消