Publishing Go Modules
Introduction
Go modules are the standard way to manage dependencies in Go projects. Publishing modules makes it possible to share your libraries and tools with the wider Go community. This tutorial will guide you through the process of publishing Go modules, from creating a module to making it available for others to use.
Prerequisites
Before you begin, ensure you have the following installed:
- Go (version 1.11 or higher)
- Git
- A GitHub account (or any other version control service)
Step 1: Create a New Go Module
First, create a new directory for your module and navigate into it:
Initialize a new Go module using the go mod init
command:
This command creates a go.mod
file that tracks your module's dependencies.
Step 2: Write Your Module Code
Create a new Go file for your module. For example, mymodule.go
:
Edit the file to include some functionality:
Here's an example of what the file might look like:
package mymodule
import "fmt"
func HelloWorld() {
fmt.Println("Hello, World!")
}
Step 3: Test Your Module
Create a test file to ensure your module works as expected. For example, mymodule_test.go
:
Edit the test file to include some tests:
Here's an example of what the test file might look like:
package mymodule
import "testing"
func TestHelloWorld(t *testing.T) {
HelloWorld()
}
Run the tests using the go test
command:
Step 4: Publish Your Module
To publish your module, you need to push it to a version control repository. Initialize a new Git repository and push your code:
Step 5: Tag a Version
Tagging a version is essential for module versioning. Create a new tag and push it:
Congratulations! Your module is now published and can be used by others.