您的位置 首页 golang

VIM 引起golang 报错 panic: template unexpected bad character

今天在调试一个 golang gin 写的网页项目时,遇到一个诡异的问题。

编译并执行 main.go

go run main.go
 

报错:

panic: template: .index.html.swp:24: unexpected bad character U+002D '-' in command
goroutine 1 [running]:
html/template.Must(...)
 /usr/local/go/src/html/template/template.go:372
github.com/gin-gonic/gin.(*Engine).Load HTML Glob(0xc0001b6280, 0xb068d2, 0x7)
 /home/zhongwei/golang/pkg/mod/github.com/gin-gonic/gin@v1.4.0/gin.go:179 +0x35c
main.main()
 /home/zhongwei/work/my_project/go/main.go:10 +0x49
exit status 2
 

我看了几遍 index.html 模板文件都没有发现任何语法和特殊字符问题。

仔细一看,实际是 .index.html.swp 文件报错。而这个文件是 VIM 产生的临时文件,只要该文件还在编辑状态,那么这个文件就会一直存在,除非关闭这个文件。

果然,关闭 VIM 之后,在执行 go run main.go 就可以编译成功了。

golang 为何会读取 .swp 文件

看了一下报错那行代码,即 main.go 的第 10 行:

router.LoadHTMLGlob("views/*")
 

猜测是 gin 默认会读取 views 目录下的所有文件,不但是 html 文件,还有 html.swp 这种临时文件。

如何排除/忽略 .swp 文件

限定 .html 后缀即可:

router.LoadHTMLGlob("views/*.html")
 

再次编译,就正常了。

gin 中 LoadHTMLGlob 与 LoadHTMLFiles 区别

  • LoadHTMLGlob 可以使用路径 通配符 。例如: router.LoadHTMLGlob(“templates/*”)
  • LoadHTMLFiles 需要指定需加装的 HTML 文件名。例如:router.LoadHTMLFiles(“templates/template1.html”, “templates/template2.html”)

文章来源:智云一二三科技

文章标题:VIM 引起golang 报错 panic: template unexpected bad character

文章地址:https://www.zhihuclub.com/100055.shtml

关于作者: 智云科技

热门文章

网站地图