Go Projects – Is It Bad to Have Source Code Outside GOPATH?

go

I am working on a new project using Go, and we are all new to Go. We are following the standard go directory structure, and having all code under

$GOPATH/src/github.com/companyname/projectname

which is also the root of a git repository

The standard recommended path layout does seem a bit strange, especially if we are working on a multi-language project, e.g. a Go based rest/http backend, and an html/javascript front-end. In that case I would probably want my project structure to look like this:

/
  doc/
  src/
    server/
      main.go
      module1/
        module.go
    client/
      index.html
  Makefile

But is it actually necessary to have the code placed inside the GOPATH?

As an attempt I created a small program where the source code was outside the GOPATH. I could easily split the project into packages, so the main package could reference a foo package in a foo/ folder using import "./foo".

As far as I can see, there are two things this disallows me:

  • Other code cannot import this code. This is not a problem as we are building a service specifically for the company.
  • I cannot use go install to install it. This is not a problem either. The build pipeline installs the tool.

It does however allow the build server to not have its workspace be located inside the GOPATH

Is such an approach discouraged? If so, why so?

Are there other negative side effects than the two I have listed?

Bear in mind that this is a private project for a company, not public open source code.

Detaching the actual project from the GOPATH seems tempting, but one should be careful in breaking the rules when you are on the Shu stage

Best Answer

2019 Update

You no longer need to store your project under GOPATH.

Put it in a directory outside of GOPATH. Then type:

go mod init github.com/youruser/yourproject

You'll be good to go.

Related Topic