Как установить gopath
Перейти к содержимому

Как установить gopath

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.

Всё, что нужно знать о 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, но его не нужно регулярно обновлять – достаточно настроить его правильно один раз.

Как установить gopath

  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

The GOPATH environment variable is a fundamental part of writing Go code without Go modules. It specifies the location of your workspace, and it defaults to $HOME/go . A GOPATH directory contains src , bin , and pkg directories. Your code is typically located in the $GOPATH/src directory.

If you are not familiar with Go and GOPATH , please first read about writing Go code with GOPATH .

If you are just starting out with Go, we recommend using Go modules instead of GOPATH.

Check the value of GOPATH

First, it’s useful to quickly check that you are using the right GOPATH . Two commands report the GOPATH value used by the VS Code Go extension: (1) Go: Current GOPATH , or (2) Go: Locate Configured Go Tools . Use either of these commands to check which GOPATH the extension is using.

If the GOPATH value is incorrect, see the details below on how to configure it.

If you have chosen not to use Go modules, you will need to configure your GOPATH .

Setting GOPATH is typically as simple as setting the environment variable once in your system’s configuration. Take a look at the Setting GOPATH Wiki if you’re unsure how to do this.

By default, the extension uses the value of the environment variable GOPATH . If no such environment variable is set, the extension runs go env and uses the GOPATH reported by the go command.

Note that, much like a PATH variable, GOPATH can contain multiple directory paths, separated by : or ; . This allows you to set different GOPATH s for different projects.

Still, there are a number of cases in which you might want a more complicated GOPATH set-up. Below, we explain more complex ways to configure and manage your GOPATH within the VS Code Go extension.

Different GOPATH s for different projects

Setting go.gopath in your user settings overrides the environment’s GOPATH value.

Workspace settings override user settings, so you can use the go.gopath setting to set different GOPATH s for different projects. A GOPATH can also contain multiple directories, so this setting is not necessary to achieve this behavior.

Automatically inferring your GOPATH

NOTE: This feature only works in GOPATH mode, not in module mode.

The go.inferGopath setting overrides the go.gopath setting. If you set go.inferGopath to true , the extension will try to infer your GOPATH based on the workspace opened in VS Code. This is done by searching for a src directory in your workspace. The parent of this src directory is then added to your global GOPATH ( go env GOPATH ).

For example, say your global GOPATH is $HOME/go , but you are working in a repository with the following structure.

If you open the foo directory as your workspace root in VS Code, «go.inferGopath» will set your GOPATH to $HOME/go:/path/to/foo/bar .

This setting is useful because it allows you to avoid setting the GOPATH in the workspace settings of each of your projects.

Install tools to a separate GOBIN

If you switch frequently between GOPATH s, you may find that the extension prompts you to install tools for every GOPATH . You can resolve this by making sure your tool installations are on your PATH , or you can configure a separate directory for tool installation: GOBIN . This environment variable tells the go command where to install all binaries. Configure it by setting:

Install tools to a separate GOPATH

NOTE: The following is only relevant if you are using a Go version that does not support Go modules, that is, any version of Go before 1.11.

Before Go 1.11, the go get command installed tools and their source code to your GOPATH . Because this extension uses a lot of different tools, this causes clutter in your GOPATH . If you wish to reduce this clutter, you can have the extension install tools to a different location. This also addresses the issue described above, when switching GOPATHs forces you to reinstall Go tools.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *