【问题标题】:Httprouter trouble with static files静态文件的Httprouter问题
【发布时间】:2015-04-25 00:05:10
【问题描述】:

我正在使用路由器 (httprouter),并希望从根目录提供静态文件。

css 文件在

static/style.css

在模板中

<link href="./static/style.css" rel="stylesheet">

main.go

router := httprouter.New()
router.ServeFiles("/static/*filepath", http.Dir("/static/"))
router.GET("/", Index)

但是http://localhost:3001/static/style.css 给了我一个 404 错误,并且渲染页面中的样式也不起作用。

【问题讨论】:

  • 省略“/static/”中的尾部斜杠?除此之外,您可以尝试将一些 Printfs 添加到路由器模块中以查看发生了什么。

标签: go


【解决方案1】:

尝试将http.Dir("/static/") 替换为http.Dir("static")(这将是静态目录的相对路径)或http.Dir("/absolute/path/to/static")。你的这个单一改变的例子对我有用。

另请参阅 httprouter 的 ServeFiles 文档:

func (r *Router) ServeFiles(path string, root http.FileSystem)

ServeFiles 提供来自给定文件系统根目录的文件。路径必须以“/*filepath”结尾,然后从本地路径/defined/root/dir/*filepath 提供文件。例如,如果 root 是“/etc”并且 *filepath 是“passwd”,则将提供本地文件“/etc/passwd”。内部使用了 http.FileServer,因此使用 http.NotFound 而不是路由器的 NotFound 处理程序。要使用操作系统的文件系统实现,请使用 http.Dir:

router.ServeFiles("/src/*filepath", http.Dir("/var/www"))

这也可能有帮助 - Third-party router and static files

我必须承认,我不清楚为什么需要两次“静态”。如果我将 http.Dir 设置为“。”这一切都适用于我需要导航到 localhost:3001/static/static/style.css

【讨论】:

    【解决方案2】:

    在调用router.ServeFiles("/static/*filepath", http.Dir("/static/")) 时,第二个参数提供根,第一个参数定义来自该根的路径。所以,试试吧

    router.ServeFiles("*filepath", http.Dir("/static"))
    

    没有提到两次/static/

    【讨论】:

    • panic: path must end with /*filepath in path '*filepath' if "/*filepath" 比 panic: path segment '/' conflicts with existing wildcard '/*filepath' in path '/'
    • 你可以试试 router.ServeFiles("static/*filepath", http.Dir("/")) 或者 router.ServeFiles("/static/*filepath", http.Dir(" ")) 与模板更加一致。任何方式都不要提及 /static/ 两次,因为 /reminder/path 附加 /root
    【解决方案3】:

    这就是我的工作方式:

    func main() {
        router := httprouter.New()
        router.GET("/", Index)
        router.ServeFiles("/static/*filepath",http.Dir("static"))
    
        log.Fatal(http.ListenAndServe(":3001", router))
    }
    

    【讨论】:

      猜你喜欢
      • 2011-06-11
      • 2011-11-21
      • 2020-11-06
      • 2018-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-20
      • 2013-11-22
      相关资源
      最近更新 更多