Adding dependency is made easy with go get
command. Specify the package needed and Go will add it to the module as a dependency. Before we get to that part let's look at how to initialize module in Go.
We can initialize the module first to create go.mod
file. This will contain details about our module
After creating a new folder for your module, run the go mod init {modulename}
command to initialize your module
go mod init helloworld
The above command creates go.mod
file with the module name "helloworld"
go get
command is the standard way of adding dependencies to your modules.
Download and install particular package using the go get {package_name}
go get github.com/gofiber/fiber/v2
The above command will install the fiber package (This is just an example and don't worry if you are not familiar with fiber)
After adding the dependency, just import it into your go file and you can start using the installed package
package main
import "github.com/gofiber/fiber/v2"
func main() {
// Staring a server
app := fiber.New()
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Hello from fiber")
})
app.Listen(":3000")
}
For more info about go get command and its arguments, check this link
When you want to remove any dependency, you need to perform a couple of steps
go mod tidy -v
command to remove any unused packageFrom the above example, we need to remove all the places where we are using fiber.
package main
func main() {
// Staring a server
}
We just have an empty main function in our example but you get the point :)
go mod tidy -v
Output:
unused github.com/gofiber/fiber
The above command is used to remove any unused dependencies from the module. Since we have removed any reference to the installed package, it will assume that that package is not needed anymore and remove it from the dependency.
go.mod
will also be updated to remove the dependency.
go mod init {packagename}
go get {packagename}
go mod tidy -v
commandMore details on the main and init functions in Go
Stay tuned by subscribing to our mailing list and joining our Discord community
Sriram is a content creator focused on providing quality content which provides value for the readers. He believe is constant learning and sharing those learning with the group. He is working as a lead developer and bulk of his experience is in working with multiple javascript frameworks such as Angular, React, Svelte. He is passionate about open source technologies and on his free time loves to develop games.
We will reach out when exciting new posts are available. We won’t send you spam. Unsubscribe at any time.