go - 运行由 Go build 创建的二进制文件时出现问题

标签 go

我有一个简单的 Go 应用程序,它有一些模板文件,我可以在其中呈现一些文本。在使用 Go build 构建我的二进制文件后,我尝试运行该文件,但出现错误:

panic: html/template: pattern matches no files: public/*.html

我正在使用 Echo 框架并按照他们的步骤为模板添加渲染。

这是我的 main.go 文件中的代码

    // TemplateRenderer is a custom html/template renderer for Echo framework
    type TemplateRenderer struct {
        templates *template.Template
    }

    // Render renders a template document
    func (t *TemplateRenderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
        return t.templates.ExecuteTemplate(w, name, data)
    }

    func main() {

        // Create a new instance of Echo
        e := echo.New()
        e.Use(middleware.Logger())
        e.Use(middleware.Recover())

        renderer := &TemplateRenderer{
            templates: template.Must(template.ParseGlob("public/*.html")),
        }
        e.Renderer = renderer

e.GET("/", func(context echo.Context) error {
        return context.Render(http.StatusOK, "index.html", api.FetchCoinList())
    })
}

我需要做些什么才能将我的模板打包到二进制文件中吗?当我运行 go run main.go

时它完美运行

最佳答案

Is there something I have to do to package my templates up in the binary?

是的,当您使用 go run main.go 运行它们时,让它们在它们所在的相同(相对)文件夹中可用

例如,如果 main.go 旁边有一个包含模板的 public 文件夹,那么请确保您“复制”了 public 可执行二进制文件旁边的文件夹。

阅读此问题+答案以获得更多选项:how to reference a relative file from code and tests

通常您应该提供定义从何处获取静态 Assets 和文件的方法。该应用程序可能有一个默认位置来查找它们,但更改此设置应该很容易(例如,通过命令行标志、通过环境变量或通过配置文件)。

另一种选择是在可执行二进制文件中包含静态文件。查看这个问题如何做到这一点:What's the best way to bundle static resources in a Go program?

关于go - 运行由 Go build 创建的二进制文件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48115540/

相关文章:

postgresql - 两种不同形式的数据库连接字符串

go - 具有导出字段的私有(private)类型

url - 在 golang 中如何拆分 URL 并从解码组件编码回 URL。有什么包裹吗?

javascript - 在 golang 中实现响应式模板

golang POST 图像和文本字段,带有 multipart/form-data

heroku - Go:部署在 Heroku 上

json - 在 Go 中创建 JSON 或 slice 数组

go - go 函数的包选择错误

database - 在 Golang 中执行 SQL 查询

go - ParseInt 不转换为所需的类型