Go 将HTML内容读入字符串

Go 将HTML内容读入字符串,go,Go,我的项目结构中有一个html文件: /pkg和/html都位于根级别 /html/sample.html 我想将这个文件加载到一个字符串中,这样我就可以将它发送到一个外部服务,该服务使用这个html发送电子邮件,这要求html采用字符串格式 /pkg/sender/sender.go if,err:=os.Stat(“../../html/sample.html”);os.IsNotExist(错误){ **//这种情况会发生** 错误。新建(“html模板不存在”) fmt.Println(“

我的项目结构中有一个html文件: /pkg/html都位于根级别

/html/sample.html

我想将这个文件加载到一个字符串中,这样我就可以将它发送到一个外部服务,该服务使用这个html发送电子邮件,这要求html采用字符串格式

/pkg/sender/sender.go

if,err:=os.Stat(“../../html/sample.html”);os.IsNotExist(错误){
**//这种情况会发生**
错误。新建(“html模板不存在”)
fmt.Println(“文件不存在”)
}
为什么说这个文件不存在

然后我想将该文件的内容转换为字符串

htmlBytes,err:=ioutil.ReadFile(“../../html/sample.html”)
如果出错!=零{
fmt.Println(“错误解析文件”)
恐慌(错误)
}
parsedHTML:=字符串(htmlBytes)

正如@Cerise指出的,Go工作区中的文件是相对于工作目录的

来,试试这个

 _, base, _, _ := runtime.Caller(0) // Relative to the runtime Dir
 dir := path.Join(path.Dir(base))
 rootDir := filepath.Dir(dir)

 // its better to use os specific path separator
 htmlDir := path.Join(rootDir, "html", "sample.html")
 htmlBytes, err := ioutil.ReadFile(htmlDir)
 // rest of your code.
您可以阅读有关运行时的更多信息。调用函数路径是相对于的,而不是使用该路径的Go源文件。