英文:
Third-party router and static files
问题
我正在使用Google App Engine上的第三方路由器(httprouter)并希望从根目录提供静态文件。
由于App Engine的原因,我需要将第三方路由器附加到DefaultServeMux
的/
路径上:
router := httprouter.New()
// 这样写会出问题,因为路径“/”重复了。
http.Handle("/", http.FileServer(http.Dir("public")))
// 由于App Engine的原因,需要这样处理。
http.Handle("/", router)
问题是这样会导致/
路径重复注册,并抛出“multiple registrations for /”的错误。
如何在根目录下提供文件,尤其是index.html
文件,并使用第三方路由器呢?
英文:
I'm using a third-party router (httprouter) on Google App Engine and would like to serve static files from root.
Because of App Engine, I need to attach the third-party router to the DefaultServeMux
on /
:
router := httprouter.New()
// Doesn't work, duplicated "/".
http.Handle("/", http.FileServer(http.Dir("public")))
// Needed because of App Engine.
http.Handle("/", router)
The problem is this duplicates the /
pattern and panics with "multiple registrations for /"
How can I serve files, especially index.html
from root and use a third-party router?
答案1
得分: 0
如果你在/
路径下提供静态文件,那么你就不能提供其他路径的文件,参考链接:https://github.com/julienschmidt/httprouter/issues/7#issuecomment-45725482
> 你不能在根目录注册一个“捕获所有”来提供文件,同时在子路径注册其他处理程序。
> 参见 https://github.com/julienschmidt/httprouter#named-parameters 中的注意事项
你应该使用Go语言在应用程序的根目录提供模板,将静态文件(CSS、JS等)放在子路径下:
router := httprouter.New()
router.GET("/", IndexHandler)
// 直接从httprouter文档中复制
router.ServeFiles("/static/*filepath", http.Dir("/srv/www/public/"))
http.Handle("/", router)
英文:
If you serve static files at /
then you can't serve any other paths as per 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
You should use Go to serve a template at the application root and static files (CSS, JS, etc) at a sub path:
router := httprouter.New()
router.GET("/", IndexHandler)
// Ripped straight from the httprouter docs
router.ServeFiles("/static/*filepath", http.Dir("/srv/www/public/"))
http.Handle("/", router)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论