我正在使用路由器(httprouter)并希望从 root 提供静态文件。
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)
Run Code Online (Sandbox Code Playgroud)
但是http://localhost:3001/static/style.css给了我一个 404 错误并且渲染页面中的样式也不起作用。
尝试替换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"))
这也可能有帮助 -第三方路由器和静态文件
我必须承认,我不清楚为什么需要两次“静态”。如果我将 http.Dir 设置为“.” 这一切都适用于我需要导航到 localhost:3001/static/static/style.css 的单一区别