Alexander Ponomarev
Alexander Ponomarev

Reputation: 2728

Where should resources be kept in golang

My application uses json configuration files and other resources. Where should I place them in my project hierarchy? I could not find the answer in http://golang.org/doc/code.html (How to Write Go Code)

Upd: The question is not about automatic distribution of resources with application but much simpler: Where should I keep my resources in project hierarchy? Is there some standard place anyone expects them to be?

Upvotes: 33

Views: 13414

Answers (2)

k_o_
k_o_

Reputation: 6288

For static resource it might be the most convenient solution to include them in the binary similar to resources in Java. Newer Go version, at least 1.18 are providing the //go:embed directive to include content:

import (
    _ "embed"
)

//go:embed myfile.txt
var myfile string

You can now use myfile in your code. E.g. IntelliJ provides also support for this.

There are also other options to include the content, e.g. as binary or dynamically, see the link.

Upvotes: 3

Caleb Spare
Caleb Spare

Reputation: 507

There is no single correct answer, nor are there any strong conventions assumed or enforced by any Go tooling at this time.

Typically I start by assuming that the files I need are located in the same directory from where the program will be run. For instance, suppose I need conf.json for myprog.go; then both of those files live together in the same directory and it works to just run something like

go build -o myprog && ./myprog

When I deploy the code, the myprog binary and conf.json live together on the server. The run/supervisor script needs to cd to that directory and then run the program.

This also works when you have a lot of resources; for instance, if you have a webserver with JS, CSS, and images, you just assume they're relative to cwd in the code and deploy the resource directories along with the server binary.

Another alternative to assuming a cwd is to have a -conf flag which the user can use to specify a configuration file. I typically use this for distributing command-line tools and open-source server applications that require a single configuration file. You could even use an -assets flag or something to point to a whole tree of resource files, if you wanted.

Finally, one more approach is to not have any resource files. go-bindata is a useful tool that I've used for this purpose -- it just encodes some data as bytes into a Go source file. That way it's all baked into your binary. I think this method is most useful when the resource data will rarely or never change, and is pretty small. (Otherwise you're going to be shipping around huge binaries.) One (kind of silly) example of when I've used go-bindata in the past was for baking a favicon into a really simple server which didn't otherwise require any extra files besides the server binary.

Upvotes: 13

Related Questions