Third-party router and static files

2019-09-03 19:17发布

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条回答
成全新的幸福
2楼-- · 2019-09-03 20:14

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)
查看更多
登录 后发表回答