-2

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

N P
  • 2,319
  • 7
  • 32
  • 54

1 Answers1

1

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?

icza
  • 389,944
  • 63
  • 907
  • 827