Package Management With Go Modules: The Pragmatic Guide
Go Modules is a way of dealing with dependencies in Go. Initially an experiment, it is is supposed to enter the playing field in 1.13 as a new default for package management.
I find it a bit unusual as a newcomer coming from other languages and so I wanted to collect some thoughts and tips to help others like me get some idea about Go package management. We’ll start with some trivia and then proceed to less obvious aspects including the use of vendor folder, using modules with Docker in development, tool dependencies etc.
If you’ve been using Go Modules for a while already and know the Wiki like the back of your hand, this article probably won’t prove very useful to you. For some, however, it may save a few hours of trial and error.
So hope in and enjoy the ride.
Quick Start
If your project is already in version control, you can simply run
Or you can supply module path manually. It’s kinda like a name, URL and import path for your package:
This command will create go.mod file which both defines projects requirements and locks dependencies to their correct versions (to give you some analogy, it’s like package.json and package-lock.json rolled into one):
Run go get to add a new dependency to your project:
Note that although you can’t specify version range with go get, what you define here anyway is a minimum version and not an exact version. As we’ll see later, there is way to gracefully bump dependencies according to semver.
Now our go.mod file looks like this:
+incompatible suffix is added for all packages that not opted in to Go Modules yet or violate its versioning guidelines.
Because we didn’t yet import the package anywhere in our project, it was marked as // indirect . We can tidy this up with the following command:
Depending on the current state of your repo, this will either prune the unused module or remove // indirect comment.
If a particular dependency does not itself have a go.mod (for example it has not yet opted in to use modules), then it will have all of its dependencies recorded in a parent go.mod file (e.g. your go.mod) file along with // indirect comment to indicate it is not from a direct import within your module.
On a more general note, the purpose of go mod tidy is to also add any dependencies needed for other combinations of OS, architecture, and build tags. Make sure to run this before every release.
See that go.sum file was also created upon adding a dependency. You may assume it’s a lock file. But in fact, go.mod already provides enough information for 100% reproducible builds. The other file is just for validation purposes: it contains the expected cryptographic checksums of the content of specific module versions.
In part because go.sum is not a lock file, it retains recorded checksums for a module version even after you stop using the module. This allows validation of the checksums if you later resume using it, which provides additional safety.
Commands like go build or go test will automatically download all the missing dependencies though you can do this explicitly with go mod download to pre-fill local caches which may prove useful in CI.
By default all our packages from all projects are downloaded into $GOPATH/pkg/mod directory. We’ll discuss this in detail later in the article.
Updating Package Versions
You may use go get -u or go get -u=patch to update dependencies to the latest minor or patch upgrades respectively.
You can’t do this for major versions though. Code opting in to Go Modules must technically comply with these rules:
- Follow semver (an example VCS tag is v1.2.3 ).
- If the module is version v2 or higher, the major version of the module must be included as a /vN at the end of the module paths used in go.mod files and in the package import path:
Apparently, this is done so different package versions could be imported in a single build (see diamond dependency problem).
In short, Go expects you to be very deliberate when doing major version bumps.
Substitute Imported Modules
You can point a required module to your own fork or even local file path using replace directive:
You can remove the line manually or run:
Managing Dependencies Per Project
Historically, all Go code was stored in one giant monorepo, because that’s how Google organizes their codebase internally and that took its toll on the design of the language.
Go Modules is somewhat of a departure from this approach. You’re no longer required to keep all your projects under $GOPATH .
However, technically all your downloaded dependencies are still placed under $GOPATH/pkg/mod . If you use Docker containers when developing stuff locally, this may become an issue because dependencies are stored outside of project path (shared with a host filesystem via a bind-mounted volume). By default, they are simply not visible from your IDE.
This is normally not a problem for other languages but something I first encountered when working on Go codebase.
Thankfully, there are multiple (undocumented, mind you) ways to address the issue.
Option 1: Set GOPATH inside your project directory
This might sound counterintuitive at first, but if are running Go from a container, you can override its GOPATH to point to the project directory so that the packages are accessible from the host:
Popular IDEs should include the option to set GOPATH on a project (workspace) level:
The only downside to this approach is that there is no interoperability with Go runtime on the host machine. You must commit to running all Go commands from inside the container.
Option 2: Vendor Your Dependencies
Another way is to copy over your project dependencies to vendor folder:
Note the vocabulary here: we are NOT enabling Go to directly download stuff into vendor folder: that’s not possible with modules. We’re just copying over already downloaded packages.
In fact, if you vendor your dependencies like in example above, then clear $GOPATH/pkg/mod , then try to add some new dependencies to your project, you will observe the following:
- Go will rebuild the download cache for all packages at $GOPATH/pkg/mod/cache .
- All downloaded modules will be copied over to $GOPATH/pkg/mod .
- Finally, Go will copy over these modules to vendor folder while pruning examples, tests and some other miscellaneous files that you do not directly depend on.
In fact there is a lot of stuff omitted from this newly created vendor folder:
The typical Docker Compose file for development looks as follows (take note of volume bindings):
Note that I do NOT commit this vendor folder to version control or expect to use it in production. This is strictly a local dev scenario you can typically find in some other languages.
However, when reading comments from some of the Go maintainers and some proposals related to partial vendoring (WUT?), I get the impression that this is not the intended use case for this feature.
One of the commenters from reddit helped me shed a light on this:
Usually people vendor their dependencies for reasons like a desire to have hermetic builds without accessing the network, and having a copy of dependencies checked-in in case github goes down or a repo disappears, and being able to more easily audit changes to dependencies using standard VCS tools, etc.
Yeah, doesn’t look like anything I might be interested in.
Go teams suggests you can routinely opt-in to vendoring by setting GOFLAGS=-mod=vendor environment variable. I don’t recommend doing this. Using flags will simply break go get without providing any other benefits to your daily workflow:
Actually, the only place where you need to opt-in for vendoring is your IDE:
After some trial and error I came with the following routine for adding vendored dependencies in this approach.
Step 1. Require
You require dependency with go get :
Step 2. Import
You then import it somewhere in your code:
Step 3. Vendor
Finally, vendor your dependencies anew:
There is a pending proposal to allow go mod vendor to accept specific module patterns which may or may not solve some of the issues with this workflow.
go mod vendor already automatically requires missing imports so step 1 is optional in this workflow (unless you want to specify version constraints). Without step 2 it won’t pick up the downloaded package though.
This approach has a better interoperability with the host system, but it’s kinda convoluted when it comes to editing your dependencies.
Personally, I think overriding GOPATH is a cleaner approach because it doesn’t compromise go get functionality. Still, I wanted to cover both strategies because vendor folder may seem natural for people coming from other languages like PHP, Ruby, Javascript etc. As you can see from shenanigans described in this article, it’s not a particularly good choice for Go.
Tool Dependencies
We might want to install some go-based tools that are not being imported, but are used as part of project’s development environment. A simple example of such tool is CompileDaemon that can watch your code for changes and restart your app.
The officially recommended approach is to add a tools.go file (the name doesn’t matter) with the following contents:
- // +build tools constraint prevents your normal builds from actually importing your tool
- import statements allow the go command to precisely record the version information for your tools in your module’s go.mod file
Well, that’s it for now. I hope you won’t be just as baffled as I was when I first started using Go Modules. You can visit Go Modules wiki for more information.
go.mod file reference
Each Go module is defined by a go.mod file that describes the module’s properties, including its dependencies on other modules and on versions of Go.
These properties include:
- The current module’s module path. This should be a location from which the module can be downloaded by Go tools, such as the module code’s repository location. This serves as a unique identifier, when combined with the module’s version number. It is also the prefix of the package path for all packages in the module. For more about how Go locates the module, see the Go Modules Reference.
- The minimum version of Go required by the current module.
- A list of minimum versions of other modules required by the current module.
- Instructions, optionally, to replace a required module with another module version or a local directory, or to exclude a specific version of a required module.
Go generates a go.mod file when you run the go mod init command. The following example creates a go.mod file, setting the module’s module path to example/mymodule:
Use go commands to manage dependencies. The commands ensure that the requirements described in your go.mod file remain consistent and the content of your go.mod file is valid. These commands include the go get and go mod tidy and go mod edit commands.
For reference on go commands, see Command go. You can get help from the command line by typing go help command-name, as with go help mod tidy .
See also
- Go tools make changes to your go.mod file as you use them to manage dependencies. For more, see Managing dependencies.
- For more details and constraints related to go.mod files, see the Go modules reference.
Example
A go.mod file includes directives as shown in the following example. These are described elsewhere in this topic.
module
Declares the module’s module path, which is the module’s unique identifier (when combined with the module version number). The module path becomes the import prefix for all packages the module contains.
For more, see module directive in the Go Modules Reference.
Syntax
Examples
The following examples substitute example.com for a repository domain from which the module could be downloaded.
- Module declaration for a v0 or v1 module:
- Module path for a v2 module:
Notes
The module path must uniquely identify your module. For most modules, the path is a URL where the go command can find the code (or a redirect to the code). For modules that won’t ever be downloaded directly, the module path can be just some name you control that will ensure uniqueness. The prefix example/ is also reserved for use in examples like these.
In practice, the module path is typically the module source’s repository domain and path to the module code within the repository. The go command relies on this form when downloading module versions to resolve dependencies on the module user’s behalf.
Even if you’re not at first intending to make your module available for use from other code, using its repository path is a best practice that will help you avoid having to rename the module if you publish it later.
If at first you don’t know the module’s eventual repository location, consider temporarily using a safe substitute, such as the name of a domain you own or a name you control (such as your company name), along with a path following from the module’s name or source directory. For more, see Managing dependencies.
For example, if you’re developing in a stringtools directory, your temporary module path might be <company-name>/stringtools , as in the following example, where company-name is your company’s name:
Indicates that the module was written assuming the semantics of the Go version specified by the directive.
For more, see go directive in the Go Modules Reference.
Syntax
Examples
- Module must run on Go version 1.14 or later:
Notes
The go directive was originally intended to support backward incompatible changes to the Go language (see Go 2 transition). There have been no incompatible language changes since modules were introduced, but the go directive still affects use of new language features:
- For packages within the module, the compiler rejects use of language features introduced after the version specified by the go directive. For example, if a module has the directive go 1.12 , its packages may not use numeric literals like 1_000_000 , which were introduced in Go 1.13.
- If an older Go version builds one of the module’s packages and encounters a compile error, the error notes that the module was written for a newer Go version. For example, suppose a module has go 1.13 and a package uses the numeric literal 1_000_000 . If that package is built with Go 1.12, the compiler notes that the code is written for Go 1.13.
Additionally, the go command changes its behavior based on the version specified by the go directive. This has the following effects:
- At go 1.14 or higher, automatic vendoring may be enabled. If the file vendor/modules.txt is present and consistent with go.mod , there is no need to explicitly use the -mod=vendor flag.
- At go 1.16 or higher, the all package pattern matches only packages transitively imported by packages and tests in the main module. This is the same set of packages retained by go mod vendor since modules were introduced. In lower versions, all also includes tests of packages imported by packages in the main module, tests of those packages, and so on.
- At go 1.17 or higher:
- The go.mod file includes an explicit require directive for each module that provides any package transitively imported by a package or test in the main module. (At go 1.16 and lower, an indirect dependency is included only if minimal version selection would otherwise select a different version.) This extra information enables module graph pruning and lazy module loading.
- Because there may be many more // indirect dependencies than in previous go versions, indirect dependencies are recorded in a separate block within the go.mod file.
- go mod vendor omits go.mod and go.sum files for vendored dependencies. (That allows invocations of the go command within subdirectories of vendor to identify the correct main module.)
- go mod vendor records the go version from each dependency’s go.mod file in vendor/modules.txt .
A go.mod file may contain at most one go directive. Most commands will add a go directive with the current Go version if one is not present.
require
Declares a module as a dependency of the current module, specifying the minimum version of the module required.
For more, see require directive in the Go Modules Reference.
Syntax
Examples
- Requiring a released version v1.2.3:
- Requiring a version not yet tagged in its repository by using a pseudo-version number generated by Go tools:
Notes
When you run a go command such as go get , Go inserts require directives for each module containing imported packages. When a module isn’t yet tagged in its repository, Go assigns a pseudo-version number it generates when you run the command.
You can have Go require a module from a location other than its repository by using the replace directive.
For more about version numbers, see Module version numbering.
For more about managing dependencies, see the following:
replace
Replaces the content of a module at a specific version (or all versions) with another module version or with a local directory. Go tools will use the replacement path when resolving the dependency.
For more, see replace directive in the Go Modules Reference.
Syntax
Examples
Replacing with a fork of the module repository
In the following example, any version of example.com/othermodule is replaced with the specified fork of its code.
When you replace one module path with another, do not change import statements for packages in the module you’re replacing.
Replacing with a different version number
The following example specifies that version v1.2.3 should be used instead of any other version of the module.
The following example replaces module version v1.2.5 with version v1.2.3 of the same module.
Replacing with local code
The following example specifies that a local directory should be used as a replacement for all versions of the module.
The following example specifies that a local directory should be used as a replacement for v1.2.5 only.
For more on using a local copy of module code, see Requiring module code in a local directory.
Notes
Use the replace directive to temporarily substitute a module path value with another value when you want Go to use the other path to find the module’s source. This has the effect of redirecting Go’s search for the module to the replacement’s location. You needn’t change package import paths to use the replacement path.
Use the exclude and replace directives to control build-time dependency resolution when building the current module. These directives are ignored in modules that depend on the current module.
The replace directive can be useful in situations such as the following:
- You’re developing a new module whose code is not yet in the repository. You want to test with clients using a local version.
- You’ve identified an issue with a dependency, have cloned the dependency’s repository, and you’re testing a fix with the local repository.
Note that a replace directive alone does not add a module to the module graph. A require directive that refers to a replaced module version is also needed, either in the main module’s go.mod file or a dependency’s go.mod file. If you don’t have a specific version to replace, you can use a fake version, as in the example below. Note that this will break modules that depend on your module, since replace directives are only applied in the main module.
For more on replacing a required module, including using Go tools to make the change, see:
- Requiring external module code from your own repository fork
- Requiring module code in a local directory
For more about version numbers, see Module version numbering.
exclude
Specifies a module or module version to exclude from the current module’s dependency graph.
For more, see exclude directive in the Go Modules Reference.
Syntax
Example
Exclude example.com/theirmodule version v1.3.0
Notes
Use the exclude directive to exclude a specific version of a module that is indirectly required but can’t be loaded for some reason. For example, you might use it to exclude a version of a module that has an invalid checksum.
Use the exclude and replace directives to control build-time dependency resolution when building the current module (the main module you’re building). These directives are ignored in modules that depend on the current module.
You can use the go mod edit command to exclude a module, as in the following example.
For more about version numbers, see Module version numbering.
retract
Indicates that a version or range of versions of the module defined by go.mod should not be depended upon. A retract directive is useful when a version was published prematurely or a severe problem was discovered after the version was published.
For more, see retract directive in the Go Modules Reference.
Syntax
Example
Retracting a single version
Retracting a range of versions
Notes
Use the retract directive to indicate that a previous version of your module should not be used. Users will not automatically upgrade to a retracted version with go get , go mod tidy , or other commands. Users will not see a retracted version as an available update with go list -m -u .
Retracted versions should remain available so users that already depend on them are able to build their packages. Even if a retracted version is deleted from the source repository, it may remain available on mirrors such as proxy.golang.org. Users that depend on retracted versions may be notified when they run go get or go list -m -u on related modules.
The go command discovers retracted versions by reading retract directives in the go.mod file in the latest version of a module. The latest version is, in order of precedence:
- Its highest release version, if any
- Its highest pre-release version, if any
- A pseudo-version for the tip of the repository’s default branch.
When you add a retraction, you almost always need to tag a new, higher version so the command will see it in the latest version of the module.
You can publish a version whose sole purpose is to signal retractions. In this case, the new version may also retract itself.
For example, if you accidentally tag v1.0.0 , you can tag v1.0.1 with the following directives:
Unfortunately, once a version is published, it cannot be changed. If you later tag v1.0.0 at a different commit, the go command may detect a mismatched sum in go.sum or in the checksum database.
Retracted versions of a module do not normally appear in the output of go list -m -versions , but you can use the -retracted to show them. For more, see go list -m in the Go Modules Reference.
Управление пакетами с помощью модулей Go: Прагматическое руководство
Модули — это способ борьбы с зависимостями в Go. Изначально представленные в качестве эксперимента, модули предполагают вывести на поле в качестве нового стандарта для управления пакетами с версии 1.13.
Я нахожу эту тему достаточно необычной для новичков, пришедших с других языков, и поэтому я решил собрать здесь некоторые соображения и советы, чтобы помочь другим, таким же как я, получить представление об управлении пакетами в Go. Мы начнем с общего знакомства, а затем перейдем к менее очевидным аспектам, включая использование папки vendor, использование модулей с Docker в разработке, зависимости инструментов и т. д.
Если вы уже знакомы с модулями Go и знаете Wiki, как свои пять пальцев, эта статья, вероятно, не будет для вас очень полезной. Но для остальных, однако, она может сэкономить несколько часов проб и ошибок.
Так что если вам по пути, запрыгивайте и наслаждайтесь поездкой.

Быстрый запуск
Если в ваш проект уже интегрировано управление версиями, вы можете просто запустить
Или указать путь к модулю вручную. Это что-то вроде имени, URL и пути импорта для вашего пакета:
Эта команда создаст файл go.mod , который одновременно определяет требования проекта и лочит зависимости на их правильные версии (в качестве аналогии для вас, это как package.json и package-lock.json , объединенные в один файл):
Запустите go get , чтобы добавить новую зависимость в ваш проект:
Обратите внимание, что хотя вы не можете указать диапазон версий с помощью go get, то что вы здесь определяете, это не конкретная, а минимальная версия. Как мы увидим позже, есть способ изящно актуализировать зависимости в соответствии с semver.
Теперь наш файл go.mod выглядит следующим образом:
Суффикс +incompatible добавляется ко всем пакетам, которые еще не настроены под модули Go или нарушают их правила управления версиями.
Поскольку мы еще нигде в нашем проекте не импортировали этот пакет, он был помечен как // indirect . Мы можем привести это в порядок с помощью следующей команды:
В зависимости от текущего состояния вашего репозитория, она либо удалит неиспользуемый модуль, либо удалит комментарий // indirect .
Если какая-либо зависимость сама по себе не имеет go.mod (например, она еще не настроена под модули), тогда все ее зависимости будут записаны в родительский файл go.mod (как вариант, ваш файл go.mod) вместе с комментарием // indirect , чтобы указать, что они там не от прямого импорта в ваш модуль.
В глобальном плане цель go mod tidy состоит также в добавлении любых зависимостей, необходимых для других комбинаций ОС, архитектур и тегов сборки. Обязательно запускайте ее перед каждым релизом.
Следите также за тем, чтобы после добавления зависимости был создан файл go.sum . Вам может показаться, что это lock-файл. Но на самом деле go.mod уже предоставляет достаточно информации для на 100% воспроизводимых сборок. Файл go.sum создается в проверочных целях: он содержит ожидаемые криптографические контрольные суммы содержимого отдельных версий модуля.
Отчасти потому, что go.sum не является lock-файлом, он сохраняет записанные контрольные суммы для версии модуля даже после того, как вы перестанете использовать этот модуль. Это позволяет проверять контрольные суммы, если вы позже возобновите его использование, что обеспечивает дополнительную безопасность.

FAQ: Должен ли я коммитить go.sum в git?
A: Определенно да. С ним обладателям ваших источников не нужно доверять другим репозиториям GitHub и владельцам пользовательских путей импорта. Уже на пути к нам нечто получше, ну а пока это та же модель, что и хэши в lock-файлах.Команды go build и go test , автоматически загрузят все отсутствующие зависимости, хотя вы можете сделать это явно с помощью go mod download , чтобы предварительно заполнить локальные кэши, которые могут оказаться полезными для CI.
По умолчанию все наши пакеты из всех проектов загружаются в каталог $GOPATH/pkg/mod . Мы обсудим это подробнее позже.
Обновление версий пакетов
Вы можете использовать go get -u или go get -u=patch для обновления зависимостей до последней минорной версии или патча соответственно.
Но вы не можете обновиться так до мажорных версий. Код, включаемый в модули Go, должен технически соответствовать следующим правилам:
- Соответствовать semver (пример тега VCS v1.2.3).
- Если модуль версии v2 или выше, мажорная версия модуля должна быть включена как /vN в конце пути модуля, используемого в файле go.mod , и в пути импорта пакета:
По-видимому, это сделано для того, чтобы разные версии пакетов могли быть импортированы в одной сборке (см. diamond dependency problem).
В двух словах, Go ожидает, что вы будете очень осмотрительны при внесении мажорных версий.
Замена импортированных модулей
Вы можете указать необходимый модуль для своего собственного форка или даже локального пути к файлу, используя директиву replace :
Вы можете удалить строку вручную или запустить:
Попроектное управление зависимостями
Исторически весь код Go хранился в одном гигантском монорепозитории, потому что именно так Google организовывает свою кодовую базу, и это сказывается на дизайне языка.
Модули Go — это своего рода отступление от этого подхода. Вам больше не нужно хранить все свои проекты в $GOPATH .
Тем не менее, технически все ваши загруженные зависимости все еще помещаются в $GOPATH/pkg/mod . Если вы используете Docker-контейнеры при локальной разработке, это может стать проблемой, поскольку зависимости хранятся вне проекта. По умолчанию они просто не видны в вашей IDE.

Обычно это не проблема для других языков, но это то, с чем я впервые столкнулся при работе с кодовой базой Go.
К счастью, есть несколько (недокументированных) способов решения этой проблемы.
Вариант 1. Установите GOPATH внутри каталога вашего проекта.
На первый взгляд это может показаться нелогичным, но если вы запускаете Go из контейнера, вы можете переопределить его GOPATH, чтобы он указывал на каталог проекта для того, чтобы пакеты были доступны из хоста:
Популярные IDE должны иметь возможность установить GOPATH на уровне проекта (рабочей области):

Единственный недостаток этого подхода — отсутствие взаимодействия со средой выполнения Go на хост-компьютере. Вы должны выполнять все команды Go внутри контейнера.
Вариант 2: Вендоринг ваших зависимостей
Еще один способ — скопировать зависимости вашего проекта в папку vendor :
Следует сразу отметить: мы НЕ разрешаем Go прямую загрузку материалов в папку vendor: с модулями это невозможно. Мы просто копируем уже загруженные пакеты.
К тому же, если вы отвендорите свои зависимости, как в примере выше, затем очистите $GOPATH/pkg/mod , а затем попробуйте добавить несколько новых зависимостей в ваш проект, вы увидите следующее:
- Go перестроит кэш загрузки для всех пакетов по $GOPATH/pkg/mod/cache .
- Все загруженные модули будут скопированы в $GOPATH/pkg/mod .
- И, наконец, Go скопирует эти модули в vendor папку, удаляя примеры, тесты и некоторые другие файлы, от которых вы напрямую не зависите.

Типичный файл Docker Compose выглядит следующим образом (обратите внимание на привязки томов):
Обратите внимание, что я НЕ комичу эту vendor -папку в систему контроля версий или не собираюсь использовать ее в продакшене. Это строго локальный сценарий разработки, который обычно можно найти в некоторых других языках.
Однако, когда я читаю комментарии от некоторых мейнтейнеров Go и некотроые предложения, связанные с частичным вендорингом (ЧЕ?), у меня складывается впечатление, что изначально эта фича предназначалась не для этого юзкейса.
Один из комментаторов на reddit помог мне пролить свет на это:
Обычно люди вендорят свои зависимости по таким причинам, как желание иметь герметичные сборки без доступа к сети, а также наличия копии готовых зависимостей в случае отказа github или исчезновения репозитория, и возможность более легкого аудита изменений в зависимостях с использованием стандартных инструментов VCS и т. д.
Да, не похоже на что-либо из того, что может меня заинтересовать.
Согласно команде Go, вы можете запросто подключить вендоринг, установив переменную среды GOFLAGS=-mod=vendor . Я не рекомендую так делать. Использование флагов просто сломает go get без предоставления каких-либо других преимуществ для вашего ежедневного рабочего процесса:

На самом деле, единственное место где вам нужно подключить вендоринг — это ваше IDE:

После нескольких проб и ошибок я пришел к следующей процедуре для добавления вендорных зависимостей в этом подходе.
Шаг 1. Требование
Вы можете потребовать зависимость с помощью go get :
Шаг 2. Импорт
Затем импортируйте его куда-нибудь в своем коде:
Шаг 3. Вендоринг
Наконец, отвендорите ваши зависимости заново:
Существует ожидающее рассмотрения предложение разрешить go mod vendor принимать определенные шаблоны модулей, которые могут решить (а могут и не решить) некоторые из проблем связанные с этим рабочим процессом.
go mod vendor уже автоматически требует пропущенные импорты, поэтому шаг 1 является необязательным в этом рабочем процессе (если вы не хотите указывать ограничения версии). Однако, без шага 2 она не подхватит загруженный пакет.
Этот подход лучше взаимодействует с хост-системой, но он довольно запутан, когда дело доходит до редактирования ваших зависимостей.
Лично я думаю, что переопределение GOPATH является более чистым подходом, поскольку он не жертвует функциональность go get . Тем не менее, я хотел показать обе стратегии, потому что папка vendor может быть привычнее для людей, пришедших с других языков, таких как PHP, Ruby, Javascript и т. д. Как вы можете увидеть из махинаций, описанных в этой статье, это не особенно хороший выбор для Go.
Зависимости инструментов
Нам может понадобиться установить некоторые инструменты на основе Go, которые не импортируются, а используются как часть среды разработки проекта. Простым примером такого инструмента является CompileDaemon, который может наблюдать за вашим кодом на предмет изменений и перезапускать ваше приложение.
Overview
This command will basically match the go.mod file with the dependencies required in the source files.
- Download all the dependencies that are required in your source files and update go.mod file with that dependency.
- Remove all dependencies from the go.mod file which are not required in the source files.
Below is the usage format for the command
With -v flag, go mod tidy will print information of all the unused modules removed from go.mod file if any
Example
Let’s see an an example. Create a module with import path as “learn“