Установка пакетов
Был такой эксперимент — dev, но он был закопан в пользу механизма модулей — go mod.
Modules, packages and versions
A module is a collection of packages that are released, versioned, and distributed together. Modules may be downloaded directly from version control repositories or from module proxy servers.
A module is identified by a module path, which is declared in a go.mod file, together with information about the module’s dependencies. The module root directory is the directory that contains the go.mod file. The main module is the module containing the directory where the go command is invoked.
Each package within a module is a collection of source files in the same directory that are compiled together. A package path is the module path joined with the subdirectory containing the package (relative to the module root). For example, the module "golang.org/x/net" contains a package in the directory "html". That package’s path is "golang.org/x/net/html".
go.work
Определяет рабочую область — набор go модулей (по умолчанию, текущая директория — активная рабочая область)
Для работы с workspace используем команды:
go work init
go work use
go work editИли golang.org/x/mod/modfile для выполнения подобных изменений программно.
Build commands
All commands that load information about packages are module-aware. This includes:
go buildgo fixgo generatego getgo installgo listgo rungo testgo vet
These commands accept the following flags, common to all module commands.
The
-modflag controls whethergo.modmay be automatically updated and whether thevendordirectory is used.-mod=modtells thegocommand to ignore the vendor directory and to automatically updatego.mod, for example, when an imported package is not provided by any known module.-mod=readonlytells thegocommand to ignore thevendordirectory and to report an error ifgo.modneeds to be updated.-mod=vendortells thegocommand to use thevendordirectory. In this mode, thegocommand will not use the network or the module cache.By default, if the
goversion ingo.modis1.14or higher and avendordirectory is present, thegocommand acts as if-mod=vendorwere used. Otherwise, thegocommand acts as if-mod=readonlywere used.
The
-modcacherwflag instructs thegocommand to create new directories in the module cache with read-write permissions instead of making them read-only. When this flag is used consistently (typically by settingGOFLAGS=-modcacherwin the environment or by runninggo env -w GOFLAGS=-modcacherw), the module cache may be deleted with commands likerm -rwithout changing permissions first. Thego clean -modcachecommand may be used to delete the module cache, whether or not-modcacherwwas used.The
-modfile=file.modflag instructs thegocommand to read (and possibly write) an alternate file instead ofgo.modin the module root directory. The file’s name must end with.mod. A file namedgo.modmust still be present in order to determine the module root directory, but it is not accessed. When-modfileis specified, an alternatego.sumfile is also used: its path is derived from the-modfileflag by trimming the.modextension and appending.sum.
Vendoring
По умолчанию, модули грузятся в кэш, но если мы хотим поработать со старыми пакетами, мы можем зафризить в папку vendor определенные версии пакетов:
go mod vendorЭто создаст папку vendor и туда скопирует все пакеты для разработки и тестов. Так же будет создан файл vendor/modules.txt, который будет содержать версии пакетов. Можем их посмотреть:
go list -m
go version -mЭти команды сравнят версии в vendor с версиями в go.mod. Если они совпадут, вылетит ошибка. Надо будет ввести go mod vendor снова.
Начиная с Go 1.14, поддержка vendor включена по умолчанию. Это значит, что go build и go test будут подгружать модули из vendor, а не идти в интернет или локальный кэш пакетов. go-команды игнорируют любые другие директории vendor, кроме той, что в корневом модуле.
go get
Обновление модулей в go.mod.
go install
Установка модулей
go mod download
Загрузка модуля в кэш модулей
go list -m
go mod edit
Редактирование и форматирование go.mod.
go mod graph
Граф зависимостей
go mod init
Инициализация модуля в директории
go mod tidy
go mod vendor
Подтягивание в папку vendor зависимостей для сборки и теста проекта
go mod verify
Проверка, что все зависимости разрешены
Last updated