第三方路由器和静态文件 [英] Third-party router and static files

查看:134
本文介绍了第三方路由器和静态文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Google App Engine上使用第三方路由器( httprouter ),并希望从根服务器提供静态文件。



由于App Engine,我需要将第三方路由器连接到 DefaultServeMux on /

  router:= httprouter.New()

//不起作用,重复/。
http.Handle(/,http.FileServer(http.Dir(public)))

//因App Engine需要。
http.Handle(/,router)

问题是这个重复 / 使用多次注册/ 的模式和恐慌



如何为文件提供服务,尤其是 index.html 从根目录并使用第三方路由器? >解决方案

如果您在 / 处提供静态文件,那么您不能按照 https://github.com/julienschmidt/httprouter/issues/7#issuecomment-45725482


您无法在根目录中注册全部捕获以提供文件服务,同时也在子路径中注册其他处理程序。
另请参阅 https://github.com/julienschmidt/httprouter#named-参数


您应该使用Go在应用程序根目录和静态文件(CSS,JS等)上提供模板,在一个子路径中:

  router:= httprouter.New()

router.GET( /,IndexHandler)
//直接从httprouter文档中删除
router.ServeFiles(/ static / * filepath,http.Dir(/ srv / www / public /))

http.Handle(/,路由器)


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?

解决方案

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)

这篇关于第三方路由器和静态文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆