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 buildorgo test: Automatically downloads dependencies and updatesgo.modandgo.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 initin the project root folder. - Using a module path that does not match the repository URL.
- Forgetting to push the
go.modand 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
| Command | Purpose |
|---|---|
| go mod init | Create a new Go module |
| go build | Compile the module and download dependencies |
| go test | Run tests and update dependencies |
| git add . && git commit -m "init" && git push | Publish 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.