GOROOT and GOPATH
Go tools expect a certain layout of the source code. GOROOT and GOPATH are environment variables that define this layout.
GOROOT is a variable that defines where your Go SDK is located. You do not need to change this variable, unless you plan to use different Go versions.
GOPATH is a variable that defines the root of your workspace. By default, the workspace directory is a directory that is named go within your user home directory (
/go for Linux and MacOS, %USERPROFILE%/go for Windows). GOPATH stores your code base and all the files that are necessary for your development. You can use another directory as your workspace by configuring GOPATH for different scopes. GOPATH is the root of your workspace and contains the following folders:
src/ : location of Go source code (for example, .go , .c , .g , .s ).
pkg/ : location of compiled package code (for example, .a ).
bin/ : location of compiled executable programs built by Go.
Consider the following animation where we change the Go SDK from 1.16.1 to 1.16.3 and assign the project GOPATH to the newly-downloaded SDK directory.
GOROOT
Configure GOROOT
To see the current value of GOROOT, open settings ( Ctrl+Alt+S ) and navigate to Go | GOROOT . Click the drop-down list and select the Go version.
If no Go version is available, click the Add SDK button to download a Go version or select a path to a local copy of Go SDK.
Select a local copy of the Go SDK
Ensure that the provided path to the folder with Go SDK includes bin and src folders.
Open settings ( Ctrl+Alt+S ) and navigate to Go | GOROOT .
Click the Add SDK button and select Local .
In the file browser, navigate to the SDK version that is on your hard drive.
Download the Go SDK
Open settings ( Ctrl+Alt+S ) and navigate to Go | GOROOT .
Click the Add SDK button () and select Download .
From the Version list, select the SDK version.
In the Location field, specify the path for the SDK. To use a file browser, click the Browse icon .
Click OK to close the Download Go SDK dialog.
As you click Apply or OK on the GOROOT page, GoLand will start downloading and unpacking the Go SDK.
GOPATH
Configuring GOPATH for different scopes
You can configure GOPATH for the following scopes:
Global GOPATH : settings apply to all projects of a specific installation of GoLand.
Project GOPATH : settings apply only to the current project.
Module GOPATH : settings apply only to one module. A module can have an SDK that is different from those configured for a project. They can also carry a specific technology or a framework.
If you specified all three scopes, GoLand selects the narrowest scope first.
Open settings ( Ctrl+Alt+S ) and navigate to Go | GOPATH .
Depending on the scope that you want to apply, select the corresponding section ( Global GOPATH , Project GOPATH , or Module GOPATH ) and click the Add button .
In the file browser, navigate to the directory that you want to associate with GOPATH.
In the following example, we configured to use different GOPATH directories for different scopes. GoLand will use the Module GOPATH as it is the narrowest scope configured.
How GOPATH and GOROOT works with asdf and GoLand
When you have multiple versions installed, you can discover where each is installed, look at the version’s GOROOT value.
GOPATH ⌗
If GOPATH is set, binaries are installed to the bin subdirectory of the first directory in the GOPATH list. Otherwise, binaries are installed to the bin subdirectory of the default GOPATH
GOPATH and GOROOT with asdf ⌗
I use asdf for development in all programming languages I use. It is fairly easy but adds complexity to manage go.
go env points out where by default go and packages are installed.
While this is ok for GOROOT , I don’t like having all packages installed in a global scope. Ideally, I want each module I develop to have its own space for packages. Having go tolling installed globally is fine and even desired.
GOPATH and GOROOT in GoLand⌗
GoLand makes it possible to download Go SDK on a per project basis. I find it unnecessary, given that I already have go managed by asdf . To pick up version of go managed by asdf , I define GOROOT as
With GOPATH I want my dependencies defined within the scope of the module. This gives me the maximum level of isolation which in turn eliminates the risks of clashing dependencies versions. I add go directory to .gitignore ( echo go >> .gitignore ) and define GOPATH in the project as <modules-path>/go .
Всё, что нужно знать о GOPATH
В этой статье мы расскажем, что такое GOPATH, как она работает и как ее настроить. Этот важнейший этап настройки рабочего окружения Go также поможет вам понять, как именно Go находит, устанавливает и собирает файлы исходного кода.
Примечание: В этой статье GOPATH – это структура папок, а $GOPATH – переменная окружения, которую Go использует для поиска структуры папок.
Рабочее пространство Go – это среда, при помощи которой Go управляет исходными файлами, скомпилированными двоичными файлами и кэшированными объектами, используемыми для более быстрой компиляции. Вы можете создать несколько таких пространств, но, как правило, для работы рекомендуется использовать только одно рабочее пространство Go. GOPATH действует как корневая папка рабочего пространства.
Настройка переменной среды $GOPATH
Переменная среды $GOPATH перечисляет места, где Go ищет рабочие пространства.
По умолчанию Go предполагает, что расположение GOPATH находится в $HOME/go, где $HOME – корневой каталог учетной записи пользователя на компьютере. Это можно изменить, установив переменную окружения $GOPATH. Более подробно эти механизмы описаны в мануале Чтение и установка переменных среды и оболочки на сервере Linux.
Для получения дополнительной информации о настройке переменной $GOPATH читайте документацию Go.
Читайте также:
$GOPATH и $GOROOT: в чем разница?
$GOROOT – это место, где хранится код, компилятор и инструменты Go, это не исходный код. $GOROOT обычно выглядит как /usr/local/go. А $GOPATH обычно выражается чем-то вроде $HOME/go.
Сегодня специально устанавливать переменную $GOROOT больше не нужно, однако она все еще упоминается в более старых материалах.
Теперь давайте обсудим структуру рабочего пространства Go.
Анатомия рабочего пространства Go
Внутри рабочей пространства Go, или внутри GOPATH, есть три каталога: bin, pkg и src. Каждый из этих каталогов имеет особое значение в цепочке инструментов Go.
Давайте рассмотрим каждый каталог более подробно.
Каталог $GOPATH/bin – это то место, куда Go помещает двоичные файлы, которые устанавливаются компилятором go. Операционная система использует переменную среды $PATH для поиска двоичных приложений, которые могут выполняться без полного пути. Рекомендуется добавить этот каталог в глобальную переменную $PATH.
Например, если вы не добавите $GOPATH/bin в $PATH для выполнения программы, вам нужно будет запустить:
Если же $GOPATH/bin добавить в $PATH, вы сможете сделать такой же вызов вот так:
В каталоге $GOPATH/pkg Go хранит предварительно скомпилированные файлы объектов, чтобы ускорить последующую компиляцию программ. Как правило, большинству разработчиков доступ к этому каталогу не нужен. Если у вас возникли проблемы с компиляцией, вы можете просто удалить этот каталог, и Go пересоберет его.
В каталоге src должны находиться все файлы .go или исходный код. Его не следует путать с исходным кодом, который использует инструмент Go, находящийся в $GOROOT. Все написанные приложения, пакеты и библиотеки Go помещаются в $GOPATH/src/path/to/code.
Что такое пакеты?
Код Go организовывается в пакеты. Пакет представляет все файлы в одном каталоге на диске. Один каталог может содержать только определенные файлы из одного пакета. Пакеты со всеми написанными пользователем исходными файлами Go хранятся в каталоге $GOPATH/src. Вы можете понять разрешение пакетов, импортируя их.
Если код находится в $GOPATH/src/blue/red, тогда имя его пакета будет red.
Оператор импорта для пакета red выглядит так:
Частью пути импорта тех пакетов, которые хранятся в репозиториях исходного кода (таких как GitHub и BitBucket) является полное местоположение репозитория.
Например, если вы импортируете исходный код по адресу https://github.com/gobuffalo/buffalo, вы будете использовать следующий путь:
Поэтому на диске этот исходный код будет находиться в этом месте:
Заключение
GOPATH – это набор папок, в которых Go ожидает найти исходный код. Теперь вы знаете, что это за папки и что они содержат. Также вы узнали, как изменить расположение по умолчанию $HOME/go на пользовательское расположение, установив переменную среды $GOPATH. Модули Go, представленные в Go 1.11, должны заменить рабочие пространства Go и GOPATH. Мы рекомендуем вам учиться использовать модули в индивидуальных проектах, однако некоторые среды, например корпоративные, могут быть не готовы к модулям.
GOPATH – один из самых хитрых аспектов настройки Go, но его не нужно регулярно обновлять – достаточно настроить его правильно один раз.
How to Write Go Code (with GOPATH)
This document demonstrates the development of a simple Go package and introduces the go tool, the standard way to fetch, build, and install Go packages and commands.
The go tool requires you to organize your code in a specific way. Please read this document carefully. It explains the simplest way to get up and running with your Go installation.
A similar explanation is available as a screencast.
Code organization
Overview
- Go programmers typically keep all their Go code in a single workspace.
- A workspace contains many version control repositories (managed by Git, for example).
- Each repository contains one or more packages.
- Each package consists of one or more Go source files in a single directory.
- The path to a package’s directory determines its import path.
Note that this differs from other programming environments in which every project has a separate workspace and workspaces are closely tied to version control repositories.
Workspaces
A workspace is a directory hierarchy with two directories at its root:
- src contains Go source files, and
- bin contains executable commands.
The go tool builds and installs binaries to the bin directory.
The src subdirectory typically contains multiple version control repositories (such as for Git or Mercurial) that track the development of one or more source packages.
To give you an idea of how a workspace looks in practice, here’s an example:
The tree above shows a workspace containing two repositories ( example and image ). The example repository contains two commands ( hello and outyet ) and one library ( stringutil ). The image repository contains the bmp package and several others.
A typical workspace contains many source repositories containing many packages and commands. Most Go programmers keep all their Go source code and dependencies in a single workspace.
Note that symbolic links should not be used to link files or directories into your workspace.
Commands and libraries are built from different kinds of source packages. We will discuss the distinction later.
The GOPATH environment variable
The GOPATH environment variable specifies the location of your workspace. It defaults to a directory named go inside your home directory, so $HOME/go on Unix, $home/go on Plan 9, and %USERPROFILE%\go (usually C:\Users\YourName\go ) on Windows.
If you would like to work in a different location, you will need to set GOPATH to the path to that directory. (Another common setup is to set GOPATH=$HOME .) Note that GOPATH must not be the same path as your Go installation.
The command go env GOPATH prints the effective current GOPATH ; it prints the default location if the environment variable is unset.
For convenience, add the workspace’s bin subdirectory to your PATH :
The scripts in the rest of this document use $GOPATH instead of $(go env GOPATH) for brevity. To make the scripts run as written if you have not set GOPATH, you can substitute $HOME/go in those commands or else run:
To learn more about the GOPATH environment variable, see ‘go help gopath’ .
Import paths
An import path is a string that uniquely identifies a package. A package’s import path corresponds to its location inside a workspace or in a remote repository (explained below).
The packages from the standard library are given short import paths such as «fmt» and «net/http» . For your own packages, you must choose a base path that is unlikely to collide with future additions to the standard library or other external libraries.
If you keep your code in a source repository somewhere, then you should use the root of that source repository as your base path. For instance, if you have a GitHub account at github.com/user , that should be your base path.
Note that you don’t need to publish your code to a remote repository before you can build it. It’s just a good habit to organize your code as if you will publish it someday. In practice you can choose any arbitrary path name, as long as it is unique to the standard library and greater Go ecosystem.
We’ll use github.com/user as our base path. Create a directory inside your workspace in which to keep source code:
Your first program
To compile and run a simple program, first choose a package path (we’ll use github.com/user/hello ) and create a corresponding package directory inside your workspace:
Next, create a file named hello.go inside that directory, containing the following Go code.
Now you can build and install that program with the go tool:
Note that you can run this command from anywhere on your system. The go tool finds the source code by looking for the github.com/user/hello package inside the workspace specified by GOPATH .
You can also omit the package path if you run go install from the package directory:
This command builds the hello command, producing an executable binary. It then installs that binary to the workspace’s bin directory as hello (or, under Windows, hello.exe ). In our example, that will be $GOPATH/bin/hello , which is $HOME/go/bin/hello .
The go tool will only print output when an error occurs, so if these commands produce no output they have executed successfully.
You can now run the program by typing its full path at the command line:
Or, as you have added $GOPATH/bin to your PATH , just type the binary name:
If you’re using a source control system, now would be a good time to initialize a repository, add the files, and commit your first change. Again, this step is optional: you do not need to use source control to write Go code.
Pushing the code to a remote repository is left as an exercise for the reader.
Your first library
Let’s write a library and use it from the hello program.
Again, the first step is to choose a package path (we’ll use github.com/user/stringutil ) and create the package directory:
Next, create a file named reverse.go in that directory with the following contents.
Now, test that the package compiles with go build :
Or, if you are working in the package’s source directory, just:
This won’t produce an output file. Instead it saves the compiled package in the local build cache.
After confirming that the stringutil package builds, modify your original hello.go (which is in $GOPATH/src/github.com/user/hello ) to use it:
Install the hello program:
Running the new version of the program, you should see a new, reversed message:
After the steps above, your workspace should look like this:
Package names
The first statement in a Go source file must be
where name is the package’s default name for imports. (All files in a package must use the same name .)
Go’s convention is that the package name is the last element of the import path: the package imported as » crypto/rot13 » should be named rot13 .
Executable commands must always use package main .
There is no requirement that package names be unique across all packages linked into a single binary, only that the import paths (their full file names) be unique.
See Effective Go to learn more about Go’s naming conventions.
Testing
Go has a lightweight test framework composed of the go test command and the testing package.
You write a test by creating a file with a name ending in _test.go that contains functions named TestXXX with signature func (t *testing.T) . The test framework runs each such function; if the function calls a failure function such as t.Error or t.Fail , the test is considered to have failed.
Add a test to the stringutil package by creating the file $GOPATH/src/github.com/user/stringutil/reverse_test.go containing the following Go code.
Then run the test with go test :
As always, if you are running the go tool from the package directory, you can omit the package path:
Remote packages
An import path can describe how to obtain the package source code using a revision control system such as Git or Mercurial. The go tool uses this property to automatically fetch packages from remote repositories. For instance, the examples described in this document are also kept in a Git repository hosted at GitHub golang.org/x/example . If you include the repository URL in the package’s import path, go get will fetch, build, and install it automatically:
If the specified package is not present in a workspace, go get will place it inside the first workspace specified by GOPATH . (If the package does already exist, go get skips the remote fetch and behaves the same as go install .)
After issuing the above go get command, the workspace directory tree should now look like this:
The hello command hosted at GitHub depends on the stringutil package within the same repository. The imports in hello.go file use the same import path convention, so the go get command is able to locate and install the dependent package, too.
This convention is the easiest way to make your Go packages available for others to use. Pkg.go.dev and the Go Wiki provide lists of external Go projects.
For more information on using remote repositories with the go tool, see go help importpath .
What’s next
Subscribe to the golang-announce mailing list to be notified when a new stable version of Go is released.
See Effective Go for tips on writing clear, idiomatic Go code.
Take A Tour of Go to learn the language proper.
Visit the documentation page for a set of in-depth articles about the Go language and its libraries and tools.