普通网友 2018-01-05 14:25
浏览 343

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

I have a simple Go application, it has a few template files where I render some text. After I build my binary with Go build I try to run the file and I get the error:

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

I am using the Echo framework and have followed their steps on adding a render for templates.

Here is the code in my main.go file

    // 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())
    })
}

Is there something I have to do to package my templates up in the binary? It works perfectly when I run go run main.go

  • 写回答

1条回答 默认 最新

  • doulouxun6756 2018-01-05 14:26
    关注

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

    Yes, make them avialable at the same (relative) folder where they are present when you run them with go run main.go.

    For example if there is a public folder containing the templates next to your main.go, then make sure you "copy" the public folder next to your executable binary.

    Read this question+answer for more options: how to reference a relative file from code and tests

    Usually you should provide ways to define where to get static assets and files from. The app may have a default place to look for them, but it should be easy to change this setting (e.g. via command line flags, via environment variables or via config files).

    Another option is to include static files in the executable binary. Check out this question how to do that: What's the best way to bundle static resources in a Go program?

    评论

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行