一个函数彻底解决vscode中运行或者调试go语言代码时相对路径视图文件路径不一致导致的异常问题

在vscode中开发go模板相关的代码时, 如果填写的是视图文件路径是相对路径,而你的main.go入口在非项目跟目录下,不同的运行方式就会造成视图文件路径的不一致, 解决方法就是通过自定义一个函数来实现,代码如下:

// 获取视图文件的地址
// vname 包含后缀的视图文件的名 如 index.html
// Author tekintian@gmail.com
func getViewFilePath(vname string) string {
	exefilepath, _ := os.Executable() // 这里获取到的可执行文件路径,在运行的debug的时候都是不一样的,debug时是在main.go所在的路径,如果是go run main.go则这个可执行路径在mac中就是类似这样的地址 /var/folders/fr/vps_kg1d365f52shzymbmv840000gn/T/go-build3845518175/b001/exe/

	var curPath string
	if strings.Contains(exefilepath, "__debug_") { // debug模式运行, 这个exefilepath就是main.go所在的路径
		curPath = filepath.Dir(exefilepath) // 获取运行文件所在的目录路径
	} else { //go run模式运行 需要区分是在vscode右上角的run还是当前目录里面的go run xx
		curPath, _ = os.Getwd()
		//判断当前目录是否包含main.go所在文件夹, 如果不包含增加 这里可兼容vscode运行 或则直接切换到目录后go run main.go运行
		if !strings.Contains(curPath, "/diyfunc") {
			curPath = fmt.Sprintf("%v/diyfunc", curPath)
		}
	}
	// 返回拼接后的视图文件的完整路径
	return fmt.Sprintf("%s/%s", curPath, vname)
}

go template中函数ParseFiles 里面的filenames这里的文件路径可以是相对路径也可以是绝对路径,相对路径是相对于当前go run或者exe所在的路径, 所以当你以不同的方式运行你的代码时这个路径就会改变,从而导致找不到模板问题

func (t *Template) ParseFiles(filenames ...string) (*Template, error)

ParseFiles parses the named files and associates the resulting templates with t. If an error occurs, parsing stops and the returned template is nil; otherwise it is t. There must be at least one file.

When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results.

ParseFiles returns an error if t or any associated template has already been executed.

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值