我在 Google App Engine 上使用第三方路由器 ( httprouter ),并希望从根目录提供静态文件。
由于 App Engine,我需要将第三方路由器附加到 /
上的 DefaultServeMux
:
router := httprouter.New()
// Doesn't work, duplicated "/".
http.Handle("/", http.FileServer(http.Dir("public")))
// Needed because of App Engine.
http.Handle("/", router)
问题是这会重复 /
模式并出现“multiple registrations for/”的 panic
如何从 root 提供文件,尤其是 index.html
并使用第三方路由器?
最佳答案
如果您在 /
提供静态文件,那么您不能根据 https://github.com/julienschmidt/httprouter/issues/7#issuecomment-45725482 提供任何其他路径。
You can't register a "catch all" at the root dir for serving files while also registering other handlers at sub-paths. See also the note at https://github.com/julienschmidt/httprouter#named-parameters
您应该使用 Go 在应用程序根目录提供模板,在子路径提供静态文件(CSS、JS 等):
router := httprouter.New()
router.GET("/", IndexHandler)
// Ripped straight from the httprouter docs
router.ServeFiles("/static/*filepath", http.Dir("/srv/www/public/"))
http.Handle("/", router)
关于google-app-engine - 第三方路由器和静态文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24849844/