gpt4 book ai didi

go - Httprouter 静态文件问题

转载 作者:IT王子 更新时间:2023-10-29 01:24:54 26 4
gpt4 key购买 nike

我正在使用路由器 ( 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 错误,渲染页面中的样式也不起作用。

最佳答案

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

另请参阅 httprouter 的 ServeFiles 文档:

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

ServeFiles serves files from the given file system root. The path must end with "/*filepath", files are then served from the local path /defined/root/dir/*filepath. For example if root is "/etc" and *filepath is "passwd", the local file "/etc/passwd" would be served. Internally a http.FileServer is used, therefore http.NotFound is used instead of the Router's NotFound handler. To use the operating system's file system implementation, use http.Dir:

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

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

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

关于go - Httprouter 静态文件问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29859453/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com