Как изменить gopath

If you are new to Go, please see the more recent How to Write Go Code.

Introduction


If you are new to Go, please see the more recent
How to Write Go Code.

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:

bin/
    hello                          # command executable
    outyet                         # command executable
src/
    golang.org/x/example/
        .git/                      # Git repository metadata
	hello/
	    hello.go               # command source
	outyet/
	    main.go                # command source
	    main_test.go           # test source
	stringutil/
	    reverse.go             # package source
	    reverse_test.go        # test source
    golang.org/x/image/
        .git/                      # Git repository metadata
	bmp/
	    reader.go              # package source
	    writer.go              # package source
    ... (many more repositories and packages omitted) ...

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:UsersYourNamego) 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:

$ export PATH=$PATH:$(go env GOPATH)/bin

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:

$ export GOPATH=$(go env GOPATH)

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:

$ mkdir -p $GOPATH/src/github.com/user

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:

$ mkdir $GOPATH/src/github.com/user/hello

Next, create a file named hello.go inside that directory,
containing the following Go code.

package main

import "fmt"

func main() {
	fmt.Println("Hello, world.")
}

Now you can build and install that program with the go tool:

$ go install github.com/user/hello

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:

$ cd $GOPATH/src/github.com/user/hello
$ go install

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:

$ $GOPATH/bin/hello
Hello, world.

Or, as you have added $GOPATH/bin to your PATH,
just type the binary name:

$ hello
Hello, world.

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.

$ cd $GOPATH/src/github.com/user/hello
$ git init
Initialized empty Git repository in /home/user/go/src/github.com/user/hello/.git/
$ git add hello.go
$ git commit -m "initial commit"
[master (root-commit) 0b4507d] initial commit
 1 file changed, 7 insertion(+)
 create mode 100644 hello.go

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:

$ mkdir $GOPATH/src/github.com/user/stringutil

Next, create a file named reverse.go in that directory with the
following contents.

// Package stringutil contains utility functions for working with strings.
package stringutil

// Reverse returns its argument string reversed rune-wise left to right.
func Reverse(s string) string {
	r := []rune(s)
	for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
		r[i], r[j] = r[j], r[i]
	}
	return string(r)
}

Now, test that the package compiles with go build:

$ go build github.com/user/stringutil

Or, if you are working in the package’s source directory, just:

$ go build

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:

package main

import (
	"fmt"

	"github.com/user/stringutil"
)

func main() {
	fmt.Println(stringutil.Reverse("!oG ,olleH"))
}

Install the hello program:

$ go install github.com/user/hello

Running the new version of the program, you should see a new, reversed message:

$ hello
Hello, Go!

After the steps above, your workspace should look like this:

bin/
    hello                 # command executable
src/
    github.com/user/
        hello/
            hello.go      # command source
        stringutil/
            reverse.go    # package source

Package names

The first statement in a Go source file must be

package name

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.

package stringutil

import "testing"

func TestReverse(t *testing.T) {
	cases := []struct {
		in, want string
	}{
		{"Hello, world", "dlrow ,olleH"},
		{"Hello, 世界", "界世 ,olleH"},
		{"", ""},
	}
	for _, c := range cases {
		got := Reverse(c.in)
		if got != c.want {
			t.Errorf("Reverse(%q) == %q, want %q", c.in, got, c.want)
		}
	}
}

Then run the test with go test:

$ go test github.com/user/stringutil
ok  	github.com/user/stringutil 0.165s

As always, if you are running the go tool from the package
directory, you can omit the package path:

$ go test
ok  	github.com/user/stringutil 0.165s

Run go help test and see the
testing package documentation for more detail.

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:

$ go get golang.org/x/example/hello
$ $GOPATH/bin/hello
Hello, Go examples!

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:

bin/
    hello                           # command executable
src/
    golang.org/x/example/
	.git/                       # Git repository metadata
        hello/
            hello.go                # command source
        stringutil/
            reverse.go              # package source
            reverse_test.go         # test source
    github.com/user/
        hello/
            hello.go                # command source
        stringutil/
            reverse.go              # package source
            reverse_test.go         # test source

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.

import "golang.org/x/example/stringutil"

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.

Getting help

For real-time help, ask the helpful gophers in #go-nuts on the
Libera.Chat IRC server.

The official mailing list for discussion of the Go language is
Go Nuts.

Report bugs using the
Go issue tracker.

Переменная среды GOPATH указывает местоположение вашего рабочего пространства. Если GOPATH не задан, предполагается, что он равен $HOME/go в системах Unix и %USERPROFILE%go в Windows. Если вы хотите использовать пользовательское местоположение в качестве своего рабочего пространства, вы можете установить переменную среды GOPATH. В этом посте объясняется, как установить эту переменную на разных платформах.

Unix системы

GOPATH может быть любым каталогом в вашей системе. В примерах Unix мы установим его в $HOME/go (по умолчанию начиная с Go 1.8). Обратите внимание, что GOPATH не должен совпадать с вашей установкой Go. Другой распространенной настройкой является установка GOPATH=$HOME.

Bash

Отредактируйте ваш ~/.bash_profile, добавив следующую строку:

export GOPATH=$HOME/go

Сохраните и выйдите из редактора. Затем отправьте ваш ~/.bash_profile как источник.

source ~/.bash_profile
Zsh

Отредактируйте файл ~/.zshrc, добавив следующую строку:

export GOPATH=$HOME/go

Сохраните и выйдите из редактора. Затем отправьте ваш ~/.zshrc как источник.

source ~/.zshrc
fish
set -x -U GOPATH $HOME/go

-x используется для указания того, что эта переменная должна быть экспортирована, а -U делает ее универсальной переменной, доступной для всех сеансов и постоянной.

Windows

Ваше рабочее пространство может быть расположено где угодно, но в этом примере мы будем использовать C:go-work.

ПРИМЕЧАНИЕ. GOPATH не должен совпадать с вашей установкой Go.

  • Создайте папку в C:go-work.
  • Щелкните правой кнопкой мыши на «Пуск» и нажмите «Панель управления». Выберите «Система и безопасность», затем нажмите «Система».
  • В меню слева выберите «Расширенные настройки системы».
  • Нажмите кнопку «Переменные среды» внизу.
  • Нажмите «Создать» в разделе «Пользовательские переменные».
  • Введите GOPATH в поле «Имя переменной».
  • Введите C:go-work в поле «Значение переменной».
  • Нажмите ОК.

Windows 10

Существует более быстрый способ редактирования переменных среды с помощью поиска:

  • Щелкните левой кнопкой мыши на «Поиск» и введите env или environment.
  • Выберите «Изменить переменные среды для вашей учетной записи».
  • … и следуйте инструкциям выше.

Windows 10 (cli версия)

  • Откройте командную строку (windows-key + r, затем введите «cmd») или окно powershell(windows-key + i)
  • Введите setx GOPATH %USERPROFILE%go (это установит GOPATH в вашу [домашняя папка]go, например, C:Usersyourusernamego
  • Закройте окно командной строки или powershell (переменная среды доступна только для новых командных строк или окон powershell, но не для текущего окна).

Читайте также:

  • Инструмент go, команды
  • Вспомогательные темы инструмента go: переменная среды GOPATH
  • Как писать Go код

Understanding GO Workspace

In our previous article we explored the go workspace in detail, in this article I will just cover the steps to set GOPATH variable.

GOPATH is an environmental variable that specifies the location of your workspace. Typically Go programmers keep all their code in a single workspace. This workspace contain directory hierarchy with three main directories at its root, namely pkg, src and bin. The GOPATH environment variable is an important part for writing Go code without Go modules.

  • pkg: The pkg directory will contain the packages and shared object files if there are any. This objects are compiled from the src directory Go source code packages.
  • src: The src directory contains your Go source files. A source file is a file that you write your  Go code into. The source file will be used by the Go compiler to create an executable binary file. The src directory typically contains multiple version control repositories such as Git. This allows for a canonical import of code in your projects. This canonical import references a fully qualified package.
  • bin: The bin directory contains executable commands. The executables are binary files that run in your system and execute tasks.

ALSO READ: Golang chi Tutorial

How to organize codes in GO

When you choose not to use Go modules, you will need to configure your GOPATH. As mentioned earlier, the workspace contains the three directories namely pkg, src and bin. To add the code to your workspace, create another directory inside the src directory with the name of your version control system e.g github.com. Move inside your version control folder and add another directory containing the repository username .Th repository username will host all your Go repositories in that respective version control. Below is an example of the workspace structure.

Set GOPATH Variable in Linux & Windows PROPERLY

To get access to your GOPATH, ensure you have Go runtime installed in your machine. You can view your current GOPATH by typing go env GOPATH in your terminal for both Linux systems and Windows. You can also get access to all Go variables that are set by Go after a successful installation. You can see all these other Go related variables by entering the go env command in your terminal.

Example

$ go env

When Go is installed in your machine , the GOPATH is set by default as of Go 1.8 . The GOPATH will be set to $HOME/go on Unix systems and %USERPROFILE%go (Windows). It is worth mentioning that since Go version 1.11, you do not have to use GOPATH anymore.

ALSO READ: Golang defer keyword — How & When to Use it?

Set GOPATH variable in Linux

Go path can be any directory in your system . In Unix for example, we set the GOPATH to $HOME/go which is the default path. Setting the GOPATH is done in a bashrc file. There are different bash files that can be present on one’s system , on Ubuntu or the linux based operating systems. It is recommended to use bashrc which can be opened by issuing the below command in your terminal. In this article we will set our GOPATH to /home/<username>/GoProjects. This workspace will host pkg, src and bin directory. The src directory will contain the github.com sub-directory .

The workspace structure will look like below.

Set GOPATH Variable in Linux & Windows PROPERLY

With our workspace created enter the below commands to set the GOPATH.

$ nano  ~/.bashrc

Add the below commands at the bottom of the .bashrc file and save the file.

export GOPATH=$HOME/GoProjects
export PATH=$PATH:$GOROOT/bin:$GOPATH/bin

Example

Set GOPATH Variable in Linux & Windows PROPERLY

To save these changes press ctrl + O then press ENTER then ctrl + X. These changes will take effect after restarting your Linux machine. Just to confirm that the go path has been set, issue the below command after restarting you machine

$ go env GOPATH

Output

/home/golinuxcloud/GoProjects

Set GOPATH variable in Windows (Using GUI)

After successfully installing Go in your windows system, create a folder anywhere in your system like the Projects folder for example. This new folder will be your workspace. Add bin, src and pkg directories in your workspace. Please follow the below steps.

  1. Go to Control Panel → All Control Panel Items → System → Advanced System Settings → Advanced → Environmental Variables.
  2. Add new system variable by clicking New on System variables → Variable name = GOPATH , Variable value = C:ProjectsGo
  3. RESTART your cmd . Your GOPATH in Windows is now set.

ALSO READ: Go if..else, if..else..if, nested if with Best Practices

To check if the path has been set correctly, enter echo %GOPATH% in the command line.

Set GOPATH variable in Windows (Using cmd)

  1. Open a command prompt by pressing win + r the enter cmd or use powershell window by pressing win + i
  2. Type go env -w GOPATH=c:Projects

Setting GOPATH in Windows 10

  1. Open a command prompt by pressing win + r the enter cmd or use powershell window by pressing win + i
  2. Enter setx GOPATH %USERPROFILE%go. (This will set the GOPATH to your <home folder>go, such as C:Usersyourusernamego.)
  3. Close the command  line . Please note that this changes will take effect on a new command line or Powershell.

Summary

GOPATH is used when a Go developer does not want to use the Go Modules. When setting a GOPATH, it should lead to a workspace with three directories namely pkg, bin, src. The source directory hosts several version control repositories that can be managed by  Git. The path to the package’s directory determines its import path.

References

https://go.dev/doc/gopath_code
https://github.com/golang/go/wiki/SettingGOPATH#windows-10-command-line

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

Setting GOPATH

The GOPATH environment variable specifies the location of your workspace. If no GOPATH is set, it is assumed to be $HOME/go on Unix systems and %USERPROFILE%go on Windows. If you want to use a custom location as your workspace, you can set the GOPATH environment variable. This page explains how to set this variable on various platforms.

  • Unix systems
    • Go 1.13
    • Bash
    • Zsh
    • fish
  • Windows
    • Go 1.13
    • Windows 10 (GUI)
    • Windows 10 (command line)

Unix systems

GOPATH can be any directory on your system. In Unix examples, we will set it to $HOME/go (the default since Go 1.8). Note that GOPATH must not be the same path as your Go installation. Another common setup is to set GOPATH=$HOME.

Go 1.13+

go env -w GOPATH=$HOME/go

Bash

Edit your ~/.bash_profile to add the following line:

Save and exit your editor. Then, source your ~/.bash_profile.

Zsh

Edit your ~/.zshrc file to add the following line:

Save and exit your editor. Then, source your ~/.zshrc.

fish

set -x -U GOPATH $HOME/go

The -x is used to specify that this variable should be exported
and the -U makes this a universal variable, available to all sessions and
persistent.

Windows

Your workspace can be located wherever you like,
but we’ll use C:go-work in this example.

NOTE: GOPATH must not be the same path as your Go installation.

  • Create a folder at C:go-work.
  • Right-click on «Start» and click on «Control Panel». Select «System and Security», then click on «System».
  • From the menu on the left, select the «Advanced system settings».
  • Click the «Environment Variables» button at the bottom.
  • Click «New» from the «User variables» section.
  • Type GOPATH into the «Variable name» field.
  • Type C:go-work into the «Variable value» field.
  • Click OK.

Go 1.13+ (command line)

  • Open a command prompt (Win + r then type cmd) or a powershell window (Win + i).
  • Type go env -w GOPATH=c:go-work.

Windows 10 (GUI)

There is a faster way to edit Environment Variables via search:

  • Left click on «Search» and type env or environment.
  • Select «Edit environment variables for your account».
  • … and follow steps above.

Windows 10 (command line)

  • Open a command prompt (Win + r then type cmd) or a powershell window (Win + i).
  • Type setx GOPATH %USERPROFILE%go. (This will set the GOPATH to your [home folder]go, such as C:Usersyourusernamego.)
  • Close the command or PowerShell window. (The environment variable is only available for new command or PowerShell windows, not for the current window.)

11 мая, 2019 12:33 пп
6 231 views
| Комментариев нет

Без категорий

В этой статье мы расскажем, что такое GOPATH, как она работает и как ее настроить. Этот важнейший этап настройки рабочего окружения Go также поможет вам понять, как именно Go находит, устанавливает и собирает файлы исходного кода.

Примечание: В этой статье GOPATH – это структура папок, а $GOPATH – переменная окружения, которую Go использует для поиска структуры папок.

Рабочее пространство Go – это среда, при помощи которой Go управляет исходными файлами, скомпилированными двоичными файлами и кэшированными объектами, используемыми для более быстрой компиляции. Вы можете создать несколько таких пространств, но, как правило, для работы рекомендуется использовать только одно рабочее пространство Go. GOPATH действует как корневая папка рабочего пространства.

Настройка переменной среды $GOPATH

Переменная среды $GOPATH перечисляет места, где Go ищет рабочие пространства.

По умолчанию Go предполагает, что расположение GOPATH находится в $HOME/go, где $HOME – корневой каталог учетной записи пользователя на компьютере. Это можно изменить, установив переменную окружения $GOPATH. Более подробно эти механизмы описаны в мануале Чтение и установка переменных среды и оболочки на сервере Linux.

Для получения дополнительной информации о настройке переменной $GOPATH читайте документацию Go.

Читайте также:

  • Установка Go и настройка локальной среды разработки в macOS
  • Установка Go и настройка локальной среды разработки в Ubuntu 18.04

$GOPATH и $GOROOT: в чем разница?

$GOROOT – это место, где хранится код, компилятор и инструменты Go, это не исходный код. $GOROOT обычно выглядит как /usr/local/go. А $GOPATH обычно выражается чем-то вроде $HOME/go.

Сегодня специально устанавливать переменную $GOROOT больше не нужно, однако она все еще упоминается в более старых материалах.

Теперь давайте обсудим структуру рабочего пространства Go.

Анатомия рабочего пространства Go

Внутри рабочей пространства Go, или внутри GOPATH, есть три каталога: bin, pkg и src. Каждый из этих каталогов имеет особое значение в цепочке инструментов Go.

.
├── bin
├── pkg
└── src
└── github.com/foo/bar
└── bar.go

Давайте рассмотрим каждый каталог более подробно.

Каталог $GOPATH/bin – это то место, куда Go помещает двоичные файлы, которые устанавливаются компилятором go. Операционная система использует переменную среды $PATH для поиска двоичных приложений, которые могут выполняться без полного пути. Рекомендуется добавить этот каталог в глобальную переменную $PATH.

Например, если вы не добавите $GOPATH/bin в $PATH для выполнения программы, вам нужно будет запустить:

$GOPATH/bin/myapp

Если же $GOPATH/bin добавить в $PATH, вы сможете сделать такой же вызов вот так:

myapp

В каталоге $GOPATH/pkg Go хранит предварительно скомпилированные файлы объектов, чтобы ускорить последующую компиляцию программ. Как правило, большинству разработчиков доступ к этому каталогу не нужен. Если у вас возникли проблемы с компиляцией, вы можете просто удалить этот каталог, и Go пересоберет его.

В каталоге src должны находиться все файлы .go или исходный код. Его не следует путать с исходным кодом, который использует инструмент Go, находящийся в $GOROOT. Все написанные приложения, пакеты и библиотеки Go помещаются в $GOPATH/src/path/to/code.

Что такое пакеты?

Код Go организовывается в пакеты. Пакет представляет все файлы в одном каталоге на диске. Один каталог может содержать только определенные файлы из одного пакета. Пакеты со всеми написанными пользователем исходными файлами Go хранятся в каталоге $GOPATH/src. Вы можете понять разрешение пакетов, импортируя их.

Если код находится в $GOPATH/src/blue/red, тогда имя его пакета будет red.

Оператор импорта для пакета red выглядит так:

import "blue/red"

Частью пути импорта тех пакетов, которые хранятся в репозиториях исходного кода (таких как GitHub и BitBucket) является полное местоположение репозитория.

Например, если вы импортируете исходный код по адресу https://github.com/gobuffalo/buffalo, вы будете использовать следующий путь:

import "github.com/gobuffalo/buffalo"

Поэтому на диске этот исходный код будет находиться в этом месте:

$GOPATH/src/github.com/gobuffalo/buffalo

Заключение

GOPATH – это набор папок, в которых Go ожидает найти исходный код. Теперь вы знаете, что это за папки и что они содержат. Также вы узнали, как изменить расположение по умолчанию $HOME/go на пользовательское расположение, установив переменную среды $GOPATH. Модули Go, представленные в Go 1.11, должны заменить рабочие пространства Go и GOPATH. Мы рекомендуем вам учиться использовать модули в индивидуальных проектах, однако некоторые среды, например корпоративные, могут быть не готовы к модулям.

GOPATH – один из самых хитрых аспектов настройки Go, но его не нужно регулярно обновлять – достаточно настроить его правильно один раз.

Tags: Go, GOPATH

You can use the «export» solution just like what other guys have suggested. I’d like to provide you with another solution for permanent convenience: you can use any path as GOPATH when running Go commands.

Firstly, you need to download a small tool named gost : https://github.com/byte16/gost/releases . If you use ubuntu, you can download the linux version(https://github.com/byte16/gost/releases/download/v0.1.0/gost_linux_amd64.tar.gz).

Then you need to run the commands below to unpack it :

$ cd /path/to/your/download/directory 
$ tar -xvf gost_linux_amd64.tar.gz

You would get an executable gost. You can move it to /usr/local/bin for convenient use:

$ sudo mv gost /usr/local/bin

Run the command below to add the path you want to use as GOPATH into the pathspace gost maintains. It is required to give the path a name which you would use later.

$ gost add foo /home/foobar/bar     # 'foo' is the name and '/home/foobar/bar' is the path

Run any Go command you want in the format:

gost goCommand [-p {pathName}] -- [goFlags...] [goArgs...]

For example, you want to run go get github.com/go-sql-driver/mysql with /home/foobar/bar as the GOPATH, just do it as below:

$ gost get -p foo -- github.com/go-sql-driver/mysql  # 'foo' is the name you give to the path above.

It would help you to set the GOPATH and run the command. But remember that you have added the path into gost‘s pathspace. If you are under any level of subdirectories of /home/foobar/bar, you can even just run the command below which would do the same thing for short :

$ gost get -- github.com/go-sql-driver/mysql

gost is a Simple Tool of Go which can help you to manage GOPATHs and run Go commands. For more details about how to use it to run other Go commands, you can just run gost help goCmdName. For example you want to know more about install, just type words below in:

$ gost help install

You can also find more details in the README of the project: https://github.com/byte16/gost/blob/master/README.md

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.

Changing GOROOT and GOPATH

GOROOT

Configure GOROOT

  • To see the current value of GOROOT, open settings (Ctrl+Alt+S) and navigate to . 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.

    Configuring GOROOT

Select a local copy of the Go SDK

Ensure that the provided path to the folder with Go SDK includes bin and src folders.

  1. Open settings (Ctrl+Alt+S) and navigate to .

  2. Click the Add SDK button the Add SDK button and select Local.

  3. In the file browser, navigate to the SDK version that is on your hard drive.

  4. Click Open.

    Select a local copy of Go SDK

Download the Go SDK

  1. Open settings (Ctrl+Alt+S) and navigate to .

  2. Click the Add SDK button (the Add SDK icon) and select Download.

  3. From the Version list, select the SDK version.

  4. In the Location field, specify the path for the SDK. To use a file browser, click the Browse icon the Browse icon.

  5. 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.

    Download 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.

Types of settings

If you specified all three scopes, GoLand selects the narrowest scope first.

  1. Open settings (Ctrl+Alt+S) and navigate to .

  2. 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 the Add button.

  3. 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.

    Configuring GOPATH for different scopes

Last modified: 12 December 2022

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    There is a set of programs to build and process Go source code. Instead of being run directly, programs in that set are usually invoked by the go program. GOPATH and GOROOT are environment variables that define a certain arrangement and organization for the Go source code. The paths of gopath and goroot can be modified explicitly if required. 

    GOPATH

    GOPATH, also called the workspace directory, is the directory where the Go code belongs. It is implemented by and documented in the go/build package and is used to resolve import statements. The go get tool downloads packages to the first directory in GOPATH. If the environment variable is unset, GOPATH defaults to a subdirectory named “go” in the user’s home directory. To check this, enter the following command:

    On Windows: C:Users%USERPROFILE%go
    On Linux: $HOME/go

    Directory for Go code

    To check the current GOPATH enter the following command:

    C:Users%USERPROFILE%go env GOPATH

    To find current GOPATH

    GOPATH contains 3 directories under it and each directory under it has specific functions:

    • src: It holds source code. The path below this directory determines the import path or the executable name.
    • pkg: It holds installed package objects. Each target operating system and architecture pair has its own subdirectory of pkg.
    • bin: It holds compiled commands. Every command is named for its source directory.

    When using modules in Go, the GOPATH is no longer used to determine imports. However, it is still used to store downloaded source code in pkg and compiled commands bin.

    GOROOT

    GOROOT is for compiler and tools that come from go installation and is used to find the standard libraries. It should always be set to the installation directory. In order to check the current GOROOT enter the following command:

    C:Users%USERPROFILE%go env GOROOT

    To find GOROOT

    It is possible to install the Go tools to a different location. This can be done by setting the GOROOT environment variable to point to the directory in which it was installed, although this is not recommended as it comes preset with the tooling. 

    Понравилась статья? Поделить с друзьями:
  • Как изменить google аккаунт на андроиде
  • Как изменить google play на другую страну
  • Как изменить google play на mir pay
  • Как изменить google assistant на алису
  • Как изменить gmail на свой домен