0
0
GoHow-ToBeginner · 3 min read

How to Add Dependency in Go Module: Simple Guide

To add a dependency in a Go module, use the go get command followed by the module path, like go get example.com/module. This updates your go.mod file and downloads the dependency automatically.
📐

Syntax

Use the go get command to add a dependency to your Go module. The general syntax is:

  • go get <module-path>@<version> - adds a specific version of the module.
  • go get <module-path> - adds the latest version.

This updates your go.mod file and downloads the dependency.

bash
go get example.com/some/module@v1.2.3
💻

Example

This example shows how to add the popular github.com/sirupsen/logrus logging package to your Go module.

go
package main

import (
	"github.com/sirupsen/logrus"
)

func main() {
	logrus.Info("Hello, Go modules!")
}
Output
INFO[0000] Hello, Go modules!
⚠️

Common Pitfalls

Common mistakes when adding dependencies include:

  • Not running go mod init first to create a module.
  • Using go get outside the module directory.
  • Forgetting to commit the updated go.mod and go.sum files.
  • Specifying incorrect module paths or versions.

Always run go get inside your module folder and check your go.mod file after.

bash
/* Wrong way: running go get outside module folder */
$ cd ~
$ go get github.com/sirupsen/logrus

/* Right way: inside module folder */
$ cd ~/my-go-project
$ go get github.com/sirupsen/logrus
📊

Quick Reference

Summary tips for adding dependencies in Go modules:

  • Run go mod init once to start your module.
  • Use go get <module-path> to add or update dependencies.
  • Check go.mod and go.sum files for changes.
  • Use semantic versioning with @vX.Y.Z to specify versions.
  • Run go mod tidy to clean unused dependencies.

Key Takeaways

Use go get <module-path> inside your module folder to add dependencies.
Always initialize your module with go mod init before adding dependencies.
Check and commit your updated go.mod and go.sum files after adding dependencies.
Specify versions with @vX.Y.Z to control dependency versions.
Run go mod tidy to remove unused dependencies and keep your module clean.