普通网友 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?

    评论

报告相同问题?

悬赏问题

  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题