Go Httprouter静态文件故障
我正在使用路由器()并希望从根目录提供静态文件 中的css文件Go Httprouter静态文件故障,go,Go,我正在使用路由器()并希望从根目录提供静态文件 中的css文件 static/style.css 模板中 梅因,加油 但给了我一个404错误和风格在渲染页面不工作太多 在callrouter.ServeFiles(“/static/*filepath”,http.Dir(“/static/”)中,第二个参数提供根,第一个参数从该根定义路径。所以,试试看 router.ServeFiles("*filepath", http.Dir("/static")) 不要提及/static/两次。尝试用
static/style.css
模板中
梅因,加油
但给了我一个404错误和风格在渲染页面不工作太多 在call
router.ServeFiles(“/static/*filepath”,http.Dir(“/static/”)
中,第二个参数提供根,第一个参数从该根定义路径。所以,试试看
router.ServeFiles("*filepath", http.Dir("/static"))
不要提及/static/两次。尝试用
http.Dir(“static”)
替换http.Dir(“/static/”)
(这将是到静态Dir的相对路径)或http.Dir(“/absolute/path/to/static”)
。你这一次改变的例子对我很有用
另请参阅httprouter的ServeFile文档:
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,这就是我如何使其工作的:
func main() {
router := httprouter.New()
router.GET("/", Index)
router.ServeFiles("/static/*filepath",http.Dir("static"))
log.Fatal(http.ListenAndServe(":3001", router))
}
是否省略“/static/”中的尾随斜杠?除此之外,您可以尝试将一些printf添加到路由器模块中,以查看发生了什么情况。
panic:path必须以路径“*filepath”中的/*filepath结尾。
if/*filepath”而不是panic:path段“/”与路径“/”中现有的通配符“/*filepath”冲突。
是否可以尝试router.servefile文件(“static/*filepath”,http.Dir(“/”)或者也许router.ServeFiles(“/static/*filepath”)、http.Dir(“”)与模板更加一致。无论如何,不要两次提到/static/因为/rementer/path附加了/root
func main() {
router := httprouter.New()
router.GET("/", Index)
router.ServeFiles("/static/*filepath",http.Dir("static"))
log.Fatal(http.ListenAndServe(":3001", router))
}