Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

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:

mkdir mymodule
cd mymodule

Initialize a new Go module using the go mod init command:

go mod init github.com/yourusername/mymodule

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:

touch mymodule.go

Edit the file to include some functionality:

nano mymodule.go

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:

touch mymodule_test.go

Edit the test file to include some tests:

nano mymodule_test.go

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:

go test

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:

git init
git add .
git commit -m "Initial commit"
git remote add origin https://github.com/yourusername/mymodule.git
git push -u origin master

Step 5: Tag a Version

Tagging a version is essential for module versioning. Create a new tag and push it:

git tag v0.1.0
git push origin v0.1.0

Congratulations! Your module is now published and can be used by others.