登录
首页 >  Golang >  Go问答

解决文件与模板不匹配的方法

来源:stackoverflow

时间:2024-03-06 13:42:25 470浏览 收藏

小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《解决文件与模板不匹配的方法》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!

问题内容

当我从除 main 之外的其他 go 文件访问文件时,如何处理文件路径。

在 other.go 文件中,我尝试运行 parsefs,但它给出了 template:pattern matches no files:templates/test.tmpl 错误。这是我的文件树。

├── go.mod
├── main
│   └── main.go
└── other
    ├── other.go
    └── templates
        └── test.tmpl

其他/other.go

package other

import (
    "embed"
    "fmt"
    "html/template"
)

var templatefs embed.fs

func check() error {
    _, err := template.new("email").parsefs(templatefs, "templates/"+ "test.tmpl")

    if err != nil {
        fmt.println(err)
    }
    return nil
}

主/main.go

func main() {
    err :=othher.Check()

    if err != nil {
        fmt.Println(err)
    }
}

正确答案


go 是一种静态链接语言。无论您编写什么源代码,最终 go 工具都会将其编译为可执行二进制文件。之后运行二进制文件将不再需要源文件。

embed 包为您提供了一种在可执行二进制文件中包含静态文件的方法,您可以在运行时访问这些静态文件(运行应用程序时不需要存在原始的包含文件)。

但是,go 工具不会神奇地找出您想要包含在二进制文件中的文件和文件夹。显然,它不会包含源或模块文件夹中的所有内容。

告诉您想要包含哪些文件的方法是在您想要存储文件的变量之前添加一个特殊的 //go:embed 注释。

因此,在您的情况下,您必须在 templatefs 变量之前添加以下注释:

//go:embed templates/*
var templatefs embed.fs

另请注意,只有导入 embed 包时嵌入才有效。这种情况“自然”发生在您的情况下,因为您使用了 embed.fs 类型(需要导入 embed 包),但是如果您将文件包含在 string[]byte 类型的变量中,则不需要导入embed,在这种情况下,您必须执行“空白”导入,例如

import _ "embed"

更多详细信息请参见 embed 的软件包文档。

查看相关问题:What's the best way to bundle static resources in a Go program?

今天关于《解决文件与模板不匹配的方法》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

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