4

Is there a standard way to READ files within the package directory?

Just as an example, I have a file "VERSION" that contains the semantic version of my package, how can I read that file within my go application once the application has been installed?

I've tried all the suggestions on this SO: Golang: How to Get the Directory of the Currently running File?

A third-party package "osext" was the only method that actually produced reliable results.

EDIT: For my specific example, go build -ldflags "-X main.VERSION X.X.X" works perfectly.

Community
  • 1
  • 1
neurosnap
  • 5,658
  • 4
  • 26
  • 30
  • 4
    After you install your package, there's no guarantee where the binary is in relation to the original source, or that the source will still be there at all. – JimB Aug 07 '15 at 14:08
  • So how could I package the file into the binary? Or is that a terrible idea? – neurosnap Aug 07 '15 at 14:12
  • 2
    Packing files into the binary: [What's the best way to bundle static resources in a Go program?](http://stackoverflow.com/questions/13904441/whats-the-best-way-to-bundle-static-resources-in-a-go-program) – icza Aug 07 '15 at 14:17
  • 3
    Put the version string in the source directly, or add it at build time with `go build -ldflags "-X main.SemVer $(cat VERSION)" my/package/` : (see http://stackoverflow.com/questions/11354518/golang-application-auto-build-versioning) – JimB Aug 07 '15 at 14:17
  • 1
    @JimB It's worth reminding that the [recommended syntax in Go 1.5+](http://tip.golang.org/doc/go1.5#link) is `-X pkg.Var=value`. – Ainar-G Aug 07 '15 at 15:02
  • @Ainar-G: yes. I didn't mention it yet, because unfortunately that syntax *doesn't* work on the current release, while the old syntax will continue to work with a warning message ;) – JimB Aug 07 '15 at 15:05
  • In my projects, I actually use git annotated tags. Whenever I want to update my package, I call `git tag -a 0.5` then in my Makefile I do `go build -ldflags "-x main.Version=`git rev-parse --abbrev-ref HEAD`" it works okay for me. The only issues, is that if your package is go get'ed you the Version will be a blank string. – THUNDERGROOVE Aug 08 '15 at 05:28

0 Answers0