go - 将 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)
解决方案
就像@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 函数的更多信息
推荐阅读
- couchdb - CouchDB 读取限制
- java - ByteArrayOutputStream 会发生什么样的 JVM 优化?
- yii2 - Yii2 从模型方法上传文件图片 beforeSave
- javascript - 在后台构建 dom-subtree
- c - Ref/DeRef 一个双指向链接列表
- webpack - 生成按条目名称分组的 Webpack 代码块列表
- html - CSS过渡使左边框消失
- asp.net - 是否可以一次加载我的整个 asp.net 站点?
- google-cloud-functions - 使用并发请求接收错误调用 google 函数
- arrays - 查找数组的左函数