3

According to the Go documentation they would like you to have a workspace that you should put all their projects in.1 However, as far as I can tell, this all falls apart as soon as you want to make a project that does not use Go exclusively.

Take a project where it is made up of many micoservices for example. Lets say that it is structured like this:

app/
    authentication/ (Using rust)
    users/ (Using NodeJS)
    posts/ (Using Go)

Only one part of the app would be written in Go, and that part is nested in a subdirectory of the app. How would I apply the Go workspace philosophy to this situation?


  1. https://golang.org/doc/code.html#Workspaces
Noah Huppert
  • 4,028
  • 6
  • 36
  • 58
  • 5
    If you put app into GOPATH and it will just work. – kostya Mar 17 '16 at 02:33
  • 1
    As @kostya said, since Go has a dependency management relying on $GOPATH, I'd put app/ into GOPATH. Otherwise, include the packages in posts/ and use relative imports. – Pandemonium Mar 17 '16 at 09:12

4 Answers4

7

Using a different GOPATH per project is a very good and simple approach. In my experience this also works better than vendor since you can also install binaries and keep them on different versions.

vg is a simple tool that helps managing workspaces, it integrates with your shell and detects automatically workspaces when you cd them.

Disclaimer: I am one of the authors of the tool.

Tommaso Barbugli
  • 11,781
  • 2
  • 42
  • 41
3

As of Go 1.11, go now has modules. Amongst other things, modules enable you to have isolated source trees (with any number of packages and their own dependencies) outside of your $GOPATH.

You create a new module by running go mod init <module name> (you must be outside of $GOPATH/src to do this). This will create a go.mod file in the current folder, and any go command you run in that folder (or any folder beneath) will use that folder as your project root.

You can read more about using go modules as workspaces in this post: https://aliceh75.github.io/using-modules-for-workspaces-in-golang (disclaimer: I wrote it), and you can read more about Go modules on the Go Modules Wiki: https://github.com/golang/go/wiki/Modules

Community
  • 1
  • 1
Alice Heaton
  • 1,140
  • 11
  • 16
2

just set GOPATH according to your go files:

GOPATH=$PROJECT_PATH/app/posts

then put your source codes under

$PROJECT_PATH/app/posts/src/package

Noah Huppert
  • 4,028
  • 6
  • 36
  • 58
ugurozgen
  • 81
  • 9
2

You can put app/ in $GOPATH/src. Then whenever you're ready to build, you specify the path of your source files, relative to where they are in GOPATH.

For example:

if your app source is in $GOPATH/src/app/ and your .go files are in $GOPATH/src/app/posts/ then you can build a source (lets say posts.go in app/posts/) with go build $GOPATH/src/app/posts/posts.go or better go build posts/posts.go with app/ as your current working directory.

Anfernee
  • 1,445
  • 1
  • 15
  • 26