How to make an open source Go module and import it into your Go application?
One of the most fascinating things about Go is its “openness”.
The openness here means that any Go program can be distributed with ease.
You can make your own open source program in Go within 5 minutes and allow them to be shared across other developers.
You can see how simple that is as you go through the following simple steps.
Step1. Create your own Go program as a Module.
Let’s say you’ve created a module that has files like this
➜ go-module-one git:(main) tree .
.
├── README.md
├── go.mod
└── pkg
└── kafka
└── consumer.go2 directories, 3 files
The structure is quite simple.
in the “pkg” directory, it has a package called “kafka” where a file named consumer.go is located.
Let’s think that this module maintains some codes to connect with “Kafka” message queue broker service.
and the source code repository is hosted here in GitHub.com
https://github.com/youngstone89/go-module-one
and the project’s module spec file looks like this
module github.com/youngstone89/go-module-onego 1.18
and what we want to do is import some exported codes in the “go-module-one” and use it. “consumer.go” has some struct and func in there for kafka connection.
Then, how do you import the kafka package from the Go application that you are writing now?
Assuming that you’ve got a Go application project structured like this
➜ go-app-one git:(main) tree .
.
├── README.md
├── cmd
│ └── app
│ └── main.go
├── go.mod
├── go.sum
└── pkg3 directories, 4 files
and somehow, you might want to use the “kafka” package existing in “go-module-one”. and you can import the module like this in your application.
of course, in the go.mod file of the app, the dependency should be listed.
in the go.mod file, it’s saying that
okay, I am going to use “go-module-one” module with release version v0.1.1
so it should be there in the “github.com/youngstone89”.
and it actually exists like this
if you run the main.go file, it runs smoothly with the imported kafka package.
➜ go-app-one git:(main) go run cmd/app/main.go
Initializing kafka client...