2015-04-25 44 views
2

我正在使用路由器(httprouter)并希望从根服务器提供静态文件。在Httprouter与静态文件的问题

static/style.css

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错误,并且渲染页面中的样式也不起作用。

+0

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

回答

4

尝试用http.Dir("static")(这将是您的静态目录的相对路径)或http.Dir("/absolute/path/to/static")替换http.Dir("/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目录/文件路径*”,http.Dir( “在/ var/www” 的))

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

我必须承认,我不清楚为什么'静态'需要两次。如果我将http.Dir设置为“。”这一切都与我需要导航到本地主机的唯一区别:3001/static/static/style.css

2

致电router.ServeFiles("/static/*filepath", http.Dir("/static/"))第二个参数提供root和第一个arg定义从根的路径。所以,尽量

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

不提/静态/两次。

+0

'panic:如果路径'/ filepath'比'panic:路径段'/'与路径'/'中的现有通配符'/ * filepath'冲突,路径必须以/ * filepath结尾'/'' –

+0

Can你可以尝试router.ServeFiles(“static/* filepath”,http.Dir(“/”))或者router.ServeFiles(“/ static/* filepath”,http.Dir(“”))与模板更加一致。任何方式不提/静态/两次,因为/提醒/路径追加/根 – Uvelichitel