1

I am using gobuffalo/packr to embed template files into my golang binary. Consider this simplified example:

package main

import (
    "github.com/gobuffalo/packr"
)

func main() {
    foo, _ := packr.NewBox("./templates").FindString("text.tpl")
    println(foo)
}

According to the packr docs, one has to run the packr2 command in order to preprocess the template files so that they can be read and embedded by the regular go-compiler when it runs afterwards.

However, I do NOT have the packr repo or the binary itself installed. That import line in the golang code is the only reference to packr on my machine. And yet, running go install still produces a binary with templates correctly embedded.

Question: How can this be? What mechanism does packr employ here to be invoked at regular build time?

(Initially I assumed that packr might just use some init() magic to trigger the preprocessing. I also played around with go-generate annotations to reproduce that behaviour. Both experiments were unsuccesful - init() functions are not run at build time; and go-generate needs to be called explicitely. That leads me to believe, packr is using somewhat more delicate magic here.)

  • 1
    "still produces a binary with templates correctly embedded." --- how did you verify that? – zerkms Sep 14 '19 at 22:04
  • @zerkms I can move the binary around and it is still able to produce the template contents. This would return filenotfound errors if they weren't embedded. – Karma Fusebox Sep 14 '19 at 22:14
  • 1
    Maybe it's just that packr knows where to look for the files. https://github.com/gobuffalo/packr/tree/master/v2#development-made-easy *"Packr takes file resolution a step further. When declaring a new box you use a relative path, ./templates. When Packr receives this call it calculates out the absolute path to that directory. By doing this it means you can be guaranteed that Packr can find your files correctly, even if you're not running in the directory that the box was created in."* – mkopriva Sep 14 '19 at 23:17
  • @mkopriva bingo! That explains why the binary can be moved around safely (thus pretending to have embedded stuff), but only works as long as the template files remain in their location. I didn't think of that. And no idea why I missed that info in the docs. If you'd like to add this as an answer, I'll gladly mark it accepted. Thank you! – Karma Fusebox Sep 14 '19 at 23:54

0 Answers0