I would like to set GOPATH using the go tool upon compilation, just like adding an include path in C/++. I want the gopath to be used only within a certain project. Can this be done without setting an environment variable?
-
On unix, prefix the `go` command with setting the env var, e.g. `GOPATH=XXX go build .` – icza Jan 24 '21 at 10:51
-
@icza thats a solution, but I would like to refrain from using environment variables in general. Plus, I'm on windows :) – Serket Jan 24 '21 at 10:52
-
You can use `go env -w GOPATH="..."`. That is not a system environment variable, but that is a global setting. – TehSphinX Jan 24 '21 at 10:57
-
`go env` has `-w` flag and `-u` flag. `-w` sets a Go environment variable and `-u` unsets it. However, there does not seem to be a way to combine it into a single command while building, so you'll need to manually set it up, run the build, then unset it. – leaf bebop Jan 24 '21 at 10:58
-
Why do you want to set the GOPATH at all (and even per projekt)? – TehSphinX Jan 24 '21 at 10:58
-
And as @TehSphinX noted, this may cause problem if there somehow other build process is caught between the set and unset, as it is global setting. – leaf bebop Jan 24 '21 at 10:58
-
@TehSphinX so if I do it your way, the environment variable will 'go out of scope' after the command ends? – Serket Jan 24 '21 at 10:59
-
@TehSphinX because I like it when all of my dependencies are in the same location, in my repository. – Serket Jan 24 '21 at 10:59
-
No, it is a global setting that stays until set otherwise. – TehSphinX Jan 24 '21 at 10:59
-
@TehSphinX is there a way to make it a 'local' environment var? – Serket Jan 24 '21 at 11:00
-
@Serket: Have you looked into working with Go modules? That is the correct way and there is no need to manipulate the GOPATH at all. – TehSphinX Jan 24 '21 at 11:00
-
@TehSphinX No I haven't. Could you explain or provide some resources for reference? – Serket Jan 24 '21 at 11:01
1 Answers
Instead of trying to have a GOPATH per project to separate dependencies, work with Go modules.
A short intro on Go modules
: https://ncona.com/2020/10/introduction-to-golang-modules/
Indepth, official intro: https://blog.golang.org/using-go-modules
My intro:
In your repository call go init yourModuleName
to start working with go modules.
Once initialized, to me the most important command is go mod tidy
. You call that and it cleans up your go.mod/go.sum files, removing what is not needed and adding what is needed.
To add a new dependency call go get dependencyname
from within your project folder to add it to your go.mod
file and be able to use it in your code.
To update a dependency, just call go get dependencyname
again and it will update the version to the latest available in go.mod
file.

- 6,536
- 1
- 24
- 34