dta43039 2014-07-20 11:04
浏览 33
已采纳

第三方路由器和静态文件

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条回答 默认 最新

  • dssjxvbv918586 2014-07-20 12:01
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向