31

我的应用程序使用 json 配置文件和其他资源。我应该将它们放在我的项目层次结构中的什么位置?我在http://golang.org/doc/code.html(如何编写 Go 代码)中找不到答案

Upd:问题不在于应用程序自动分配资源,而更简单:我应该将资源保存在项目层次结构中的什么位置?有没有人期望他们成为标准的地方?

4

1 回答 1

11

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.

于 2013-10-30T22:39:27.943 回答