登录
首页 >  Golang >  Go问答

将 HTML 内容提取为字符串

来源:stackoverflow

时间:2024-02-17 09:21:25 372浏览 收藏

golang学习网今天将给大家带来《将 HTML 内容提取为字符串》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!

问题内容

我的项目结构中有一个 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函数的更多信息here

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《将 HTML 内容提取为字符串》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>