Third-party router and static files

血红的双手。 提交于 2019-12-12 01:57:39

问题


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:


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)


来源:https://stackoverflow.com/questions/24849844/third-party-router-and-static-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!