0
0
GoHow-ToBeginner · 3 min read

How to Create and Publish a Go Module Easily

To create a Go module, run go mod init <module-name> in your project folder to generate a go.mod file. Publish your module by pushing the code to a public Git repository like GitHub, then others can use it by importing your module path.
📐

Syntax

Creating a Go module involves initializing a go.mod file that defines your module path and dependencies.

  • go mod init <module-path>: Creates a new module with the given path.
  • go build or go test: Automatically downloads dependencies and updates go.mod and go.sum.
  • git push: Publishes your module code to a remote repository.
bash
go mod init github.com/username/mymodule
💻

Example

This example shows how to create a simple Go module, write a function, and publish it by pushing to GitHub.

go
package greetings

import "fmt"

// Hello returns a greeting message.
func Hello(name string) string {
    return fmt.Sprintf("Hello, %s!", name)
}
⚠️

Common Pitfalls

Common mistakes include:

  • Not running go mod init in the project root folder.
  • Using a module path that does not match the repository URL.
  • Forgetting to push the go.mod and source files to the remote repository.
  • Trying to import the module before it is publicly accessible.

Always ensure your repository is public or accessible to users who want to import your module.

bash
Wrong:
# Running go mod init with a wrong module path
$ go mod init mymodule

Right:
# Use full repository path
$ go mod init github.com/username/mymodule
📊

Quick Reference

CommandPurpose
go mod init Create a new Go module
go buildCompile the module and download dependencies
go testRun tests and update dependencies
git add . && git commit -m "init" && git pushPublish module code to remote repository
import ""Use the published module in other projects

Key Takeaways

Run 'go mod init ' in your project root to create a Go module.
Use a module path that matches your repository URL for easy publishing.
Push your code and go.mod file to a public Git repository to publish your module.
Others can import your module by using its full module path.
Check for common mistakes like wrong module paths or missing pushes.