How to make an open source Go module and import it into your Go application?

Importing Go Modules from upstream repository

김영석
2 min readAug 19, 2022

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.go
2 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.

consumer.go

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
└── pkg
3 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.

main.go importing kafka package from go-module-one

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...

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

김영석
김영석

Written by 김영석

I love problem solving and hate repetition of tedious tasks. I like automating, streamlining, optimizing, things.

No responses yet

Write a response