首页 > 解决方案 > 将 HTML 内容读入字符串

问题描述

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

/html/sample.html

我想将此文件加载到字符串中,以便可以将其发送到外部服务,该服务使用此 html 发送电子邮件,这需要 html 为字符串格式。

/pkg/sender/sender.go

if _, err := os.Stat("../../html/sample.html"); os.IsNotExist(err) {
    **// this happens**
    errors.New("The html template does not exist")
    fmt.Println("file does not exist")
}

为什么说文件不存在?

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

htmlBytes, err := ioutil.ReadFile("../../html/sample.html")
if err != nil {
    fmt.Println("error parsing file")
    panic(err)
}
parsedHTML := string(htmlBytes)

标签: go

解决方案


就像@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.

您可以在此处阅读有关 runtime.Caller 函数的更多信息


推荐阅读