CodeGym /Cursos /Go SELF /go mod tidy y go get — gestion de versiones

go mod tidy y go get — gestion de versiones

Go SELF
Nivel 35, Lección 1
Disponible

1. Why, anyway, are there two commands: go get and go mod tidy

When a project is small, it seems that dependencies “just appear somehow”: you import a package — and everything builds. But as soon as you start using external libraries (not from the standard library), the project gets another important task: to pin exactly which versions of external code you use, so the build is reproducible. And this is where Go behaves like an adult: it does not just “download something from the internet”, but carefully writes your choice into the project files.

In this lecture we will examine two commands that most often cause either respect or a bit of panic (usually both at once): go get and go mod tidy. Let us agree right away: we are not going deep into replace, vendor, and other “Swiss army knives” of the module system. Our goal is to learn how to manage dependency versions and keep things tidy in go.mod/go.sum.

The mental model: what actually counts as a “dependency”

Put simply, a dependency appears when your code imports a package that is not part of the standard library. The standard library is fmt, strings, time, net/http, and friends. Anything that looks like github.com/... or golang.org/x/... is external.

Then comes the important part. Go thinks not in “packages” but in modules. One module can contain many packages. You import a package, but you pin the module and its version in go.mod. That is why sometimes you import golang.org/x/net/html, while go.mod pins the module golang.org/x/net as a whole.

And one more key point: dependencies can be direct (direct) and transitive (transitive). Direct ones are what you import yourself. Transitive ones are what your dependencies import. It is like meeting through friends: you invited one person, and they came with friends (sometimes useful, sometimes noisy — but such is life).

2. What go get does: “choose a version and record the choice”

go get is a command about choosing module versions. Not about “downloading a library”, not about “installing everything on the computer”, but specifically about saying: “project, take this dependency in this version”. After that, Go updates go.mod and (almost always) go.sum.

There is a useful detail: modern go commands often do not try to fix the problem automatically, but instead show an error and explicitly recommend the command you should run. For example, during a build you may see a message like: “no required module provides package ...; to add it: go get ...”. This is a normal scenario: Go does not “silently do magic”, but tells you exactly what is wrong and what next step is expected.

Basic scenario: “add a dependency by import”

Let us imagine that in our training app todoapp we want to add a small feature: normalize task titles not only with strings.TrimSpace, but also, say, prepare for more complex text processing. For example, let us take the external package golang.org/x/net/html (it is common in the real world and works well as a “training” dependency).

Suppose you added an import to the code, and then run a build:

go build ./...

If the module has not been added, Go may emit an error and the hint “to add it: go get ...”. This style of message is typical for module-aware mode and is deliberately designed so that you do not have to guess which command to enter.

After that you run:

go get golang.org/x/net/html

And now Go does important things: it chooses the version of the module golang.org/x/net, writes it to go.mod, and adds checksums to go.sum.

Version management: @version, @latest, rollback

It is very useful to think of go get as a “version switch”.

You can specify a version explicitly:

go get golang.org/x/net@v0.20.0

You can ask for “the newest one” that fits the version selection rules:

go get golang.org/x/net@latest

And yes, you can roll back to an older one:

go get golang.org/x/net@v0.19.0

It is important to get used to the idea: go get is not “install the library”, but “change the project’s version requirements”. That is why after it there is almost always a diff in go.mod/go.sum. And that is normal.

4. What go mod tidy does: “clean up and synchronize facts”

If go get is a command about “choosing versions”, then go mod tidy is a command about “let us bring the dependency declaration into line with reality”.

Reality has two sides: your code and your tests. go mod tidy looks at imports in source files and in _test.go files, and does two main things: adds what is missing for building/testing, and removes what is no longer used. In the process, both go.mod and go.sum are updated.

Think of go.mod as a shopping list, and the project as your kitchen. go mod tidy is when you do not just buy milk (go get), but also throw out of the shopping list the “mango” that you added in a burst of enthusiasm two weeks ago and never actually bought.

5. Useful nuances

Why go.mod gets // indirect

Beginners often perceive // indirect as something like “this is a second-class dependency”. In reality it is just a hint: the dependency is not imported directly by your code, but is needed for the build because of other modules.

go mod tidy is exactly the command that likes to place these markers and remove them when the situation changes. An important psychological point: do not fight // indirect manually, do not delete them “for beauty” or add them “to make things right”. The tool determines correctness, and your job is to understand the meaning and keep the project in a buildable state.

Mini-table: who is responsible for what

After the theory, it is useful to reinforce who is “in charge” in which situations. The table is small, but it often saves 20 minutes of frustration.

Situation in the project What you want to do The command that is usually appropriate What will change
You added a new import of an external package, and the build complains Pin the module and version
go get <module-or-package>
go.mod, go.sum
You want to update a dependency to a specific version Choose a version
go get <module>@<version>
go.mod, go.sum
You removed an import/code, but dependencies remained as a “tail” Remove the extra stuff
go mod tidy
go.mod, go.sum
You suspect that go.mod and the code have “drifted apart” Synchronize the facts
go mod tidy
go.mod, go.sum

The phrase worth remembering is: go get is about versions, go mod tidy is about order.

6. Example on todoapp

Let us imagine the project structure (simplified):

todoapp/
  go.mod
  go.sum
  cmd/todoapp/main.go
  internal/todo/normalize.go

Add a normalization function without external dependencies

Let us start with something simple and familiar. File internal/todo/normalize.go:

package todo

import "strings"

// NormalizeTitle brings the title to a neat form.
func NormalizeTitle(s string) string {
	return strings.TrimSpace(s)
}

And now use this in cmd/todoapp/main.go:

package main

import (
	"fmt"

	"example.com/todoapp/internal/todo"
)

func main() {
	fmt.Println(todo.NormalizeTitle("   buy milk   ")) // buy milk
}

So far everything lives on the standard library, so dependencies do not change.

Add an external import to demonstrate the mechanism

Now let us add an “artificial” (but plausible) reason to use an external package. For example, we want to parse some HTML in the future (even if it is just a training example). Let us change normalize.go by adding a reference to a type from golang.org/x/net/html:

package todo

import (
	"strings"

	"golang.org/x/net/html"
)

// NormalizeTitle brings the title to a neat form.
func NormalizeTitle(s string) string {
	_ = html.Node{} // just so the import is "live"
	return strings.TrimSpace(s)
}

Most likely, after this go build ./... will start complaining that the required module has not been added and will suggest running go get. This hint format is the expected behavior of the Go tools.

Fix it by running:

go get golang.org/x/net/html

After that, open go.mod: there will be a require for golang.org/x/net .... Entries will appear in (or be updated in) go.sum.

Remove the external import and clean up the leftovers

Suppose you changed your mind, removed html.Node{} and the import itself. After that the project builds again, but the dependency may still remain in go.mod, because you added it at some point.

That is when go mod tidy comes in:

go mod tidy

This command synchronizes dependencies with the actual imports. It will remove from go.mod what is no longer needed, and clean up go.sum. This is expected: both commands manage these files for their intended purposes.

7. How to read go.mod and not fear go.sum

When you work in a team or simply value neatness, you will see diffs in go.mod and go.sum. This is a normal part of life in a Go project.

go.mod is readable and relatively “human-friendly”. There you can see module, go, and the require list. It can be read, and sometimes even edited manually (but carefully and with understanding of the consequences).

go.sum is not a “second go.mod”. It stores module checksums and is used for integrity and reproducibility checks. It is better to treat it as a product of the tools. In real practice, almost always the right path is this: you change code and versions with commands, and go.sum is updated automatically. Editing go.sum by hand usually ends with you either breaking the build, or, a minute later, running go mod tidy anyway and the tool bringing everything back.

8. The dependency lifecycle diagram

Sometimes it is useful to see the process as a “pipeline”, not as a set of random commands.

flowchart TD
    A[Added an external package import to the code] --> B[go build ./... or go test ./...]
    B -->|error: no module| C[go get <module/package>]
    C --> D[go.mod/go.sum updated]
    D --> E[the code builds again]
    E --> F[removed the import/code]
    F --> G[go mod tidy]
    G --> H[go.mod/go.sum synchronized]

The rhythm matters here: go get usually appears when you add dependencies or change versions, while go mod tidy appears when you want the dependency files to match the current state of the code again.

9. Common mistakes

Mistake #1: treating go get as “just download the library once”.
That mindset comes from a world where you manually install packages into the system. In Go it works differently: go get pins dependency versions specifically for the current module and changes go.mod/go.sum. So “I just wanted to download it” turns into a diff in the repository — and that is not a bug, but the point of the command.

Mistake #2: running go mod tidy without understanding that it also considers tests.
Sometimes a student removes an import from the main code, runs go mod tidy, and the dependency somehow remains. A common reason is that the import lives in _test.go. This is not “Go being stubborn”; it is you forgetting that tests are also part of the project, and their build needs dependencies too.

Mistake #3: editing go.sum by hand to “make it match”.
go.sum is not a place for manual creativity. If you see it changed, this is usually a consequence of changing dependencies or their versions. The right action is to understand the reason (what was added, updated, or removed), not to “twiddle the file”, because the tool will still verify integrity and may regenerate the entries again.

Mistake #4: confusing a package import path and a module path with go get.
Sometimes people run go get with one path, but import another, and the feeling of “magic” begins. The rule is simple: you can point go get either at a specific package (.../html) or at the module root (.../net). Go will figure out which module is needed. But it is important that the import in the code is correct and matches the real package location.

Mistake #5: being scared of changes in go.mod after go get or go mod tidy.
Go tools naturally update dependency files because their main job is to manage project dependencies, and both go get and go mod tidy do this by design. If every time you try to “roll it back because it is scary”, you deprive the project of its main advantage: reproducibility.

1
Tarea
Go SELF, nivel 35, lección 1
Bloqueada
Dependencias de pruebas
Dependencias de pruebas
Comentarios
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION