Building, Testing, and Publishing Go Packages: Best Practices


In my previous article, we created a self-deployable Go-based URL Shortener Service and deployed it using AWS SAM.

Now, let’s take things a step further by learning how to package and publish a Go module on the Golang package manager (pkg.go.dev) so that it’s available for the open-source community. šŸš€



Getting Started

We’ll use the shrinkIt module from my GitHub repository. You can clone it from here:
šŸ‘‰ ShrinkIt Repository

Before publishing, let’s make sure the project is clean and production-ready.



Step 1: Verify Dependencies

Run the following command to clean up and verify module dependencies:

go mod tidy
Enter fullscreen mode

Exit fullscreen mode

This ensures your go.mod and go.sum files are correct and only contain the dependencies you actually need.



Step 2: Run Tests

Always test your module before publishing to ensure everything works as expected:

go test
Enter fullscreen mode

Exit fullscreen mode

If your tests pass, you’re ready to move forward.



Step 3: Commit Changes

Use Conventional Commits when pushing changes. This helps with semantic versioning, which is crucial when publishing Go packages.

git add .
git commit -m "feat: add new feature" 
git push origin main
Enter fullscreen mode

Exit fullscreen mode



Step 4: Tag Your Release

Now, assign a version tag to your commit. For example, version v0.1.0:

git tag v0.1.0
git push origin v0.1.0
Enter fullscreen mode

Exit fullscreen mode

You should now see the tag under the Tags section in your remote Git repository.



Step 5: Publish to the Go Package Manager

Finally, publish your package to pkg.go.dev using the Go proxy:

GOPROXY=proxy.golang.org go list -m github.com/ticatwolves/shrinkit@v0.1.0

Enter fullscreen mode

Exit fullscreen mode

šŸ‘‰ Note: You can change the GOPROXY depending on whether you want to test or publish to the production package manager.



Step 6: Use Your Package

Once published, your package is available for anyone to use in their projects:

go get github.com/ticatwolves/shrinkit@v0.1.0

Enter fullscreen mode

Exit fullscreen mode

Congratulations šŸŽ‰ — you’ve published your first Go package to the public!



What’s Next?

That’s it for now! Join us in our next article, where we’ll explore how to add a CI/CD pipeline for automated building, testing, and publishing of your Go packages.

šŸ’¬ How do you handle versioning and publishing in your Go projects? Share your workflow in the comments — I’d love to learn from your experience!

šŸ“š Further Reading & References



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *