Chose Language:
comments
Author: Admin/Publisher |finished | checked

Go Modules

In this section, we will look at Go modules. It’s been a while since GOPATH started being replaced by this new way of managing the dependencies that make up our project. GOPATH is still usable but is becoming obsolete.

The use of modules is recommended by the Go development team.

What are Go modules?

Modules are a collection of packages stored in a file tree that contains a go.mod file.

Ultimately, our project is a module that can depend on other modules.

If we open a go.mod file in any text editor, we will see the dependencies of our project.

What else can I see in the go.mod file?

· List of dependencies:
Modules that your project depends on to function.

· Versions of dependencies:
Specific versions of each module being used.

· Transitive dependencies:
Modules that the direct dependencies depend on.

Modules can only be used as long as the predefined environment variable GO111MODULE is set to on.

If you wish, you can learn more about these environment variables at: Frequently Used Predefined Environment Variables in Go

go.mod

There are a number of commands that can be used to work with the go.mod file.

In Go, creating the go.mod file is simple; you just need to run the command go mod init to create it. This command creates the initial go.mod file for our project.

you have to use go mod init in your project folder
go mod init

There are other commands that can also make modifications to go.mod, for example:

The command go mod tidy will clean up dependencies that the project doesn’t need and add new dependencies that we have added.

Project folder
go mod tidy

Also, on the other hand, we have the command go mod vendor which, although its use is discouraged, serves for building the project. This command creates a vendor folder with the dependencies. If you do not run the build with the vendor folder, the created .exe file might not work correctly.

As of Go 1.18, it is no longer necessary to run go mod vendor; the download of necessary modules will be automatic by default. It is important to note that this fully depends on your internet connection.

Project folder
go mod vendor

We can verify the dependencies of the modules we use with go mod verify.

To add modules to our project, we have the command go get, although it has been increasingly replaced by go install. Therefore, if at any point you cannot use the module with go get, try using go install.

You can see more commands for modules at https://go.dev/ref/mod.

Category: en-go
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category

Comments