How to Create Modules in Golang?


Golang, also known as Go, is a popular programming language that provides support for modules. Modules are a way to manage the dependencies of your Go code, and they help you avoid version conflicts and simplify your build process.

In this article, we will discuss how to create modules in Golang step by step.

Step 1: Enable Module Mode

To create a new module in Golang, you need to first enable module mode. You can do this by setting the environment variable GO111MODULE to on −

export GO111MODULE=on

You can also set this variable on a per-project basis by creating a file named go.mod in the root of your project.

Step 2: Create a New Module

Once you have enabled module mode, you can create a new module by running the following command −

go mod init <module-name>

Replace <module-name> with the name of your module. For example −

go mod init example.com/my-module

This will create a new go.mod file in the root of your project. This file will contain the name of your module, as well as any dependencies you add in the future.

Step 3: Add Dependencies

To add dependencies to your module, you can use the go get command −

go get <dependency-name>

For example, to add the popular Gorilla web toolkit to your module, you can run −

go get github.com/gorilla/mux

This will download the Gorilla mux library and add it as a dependency in your go.mod file.

Step 4: Build and Test Your Module

Once you have added your dependencies, you can build and test your module using the standard go build and go test commands −

go build
go test

These commands will build and test your module, along with any dependencies you have added.

Step 5: Publish Your Module

Once you are satisfied with your module, you can publish it to the public Go module repository or a private repository of your choice. You can do this using the go command −

go mod tidy
go mod vendor
go mod verify

These commands will tidy up your module, vendor its dependencies, and verify that everything is working correctly.

Conclusion

Creating modules in Golang is a straightforward process that can help you manage your dependencies and simplify your build process. By following the steps outlined in this article, you can create and publish your own modules with ease.

Updated on: 05-May-2023

87 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements