How Code is organized in Go?
In Go, the smallest unit of code is “Package”.
Package is a collection of go source files that have “.go” suffix in the same directory.
Let’s say we have an “api” package under pkg directory of an application project, and it looks like this :
pkg/api
├── goodbyeworld.go
└── helloworld.go
0 directories, 2 files
the “api” is a package.
and in the go source code files, the package name is declared like this
at line 1, “package api” declares what package the helloworld.go file belongs to. That way, the basic organization of go files are happening.
let’s look inside what it looks like in goodbyeworld.go
it’s just the same as in the helloworld.go
package name is “api” so we tell the go compiler that the 2 files are contained in the same package.
But be aware that the package name isn’t always the same as the directory name.
Let’s say we have some codes in “elasticsearch” directory under pkg
pkg/elasticsearch
└── es.go
at line 1, the package name is declared to be “es”, not “elasticsearch”.
then, how that affects “import” statement in the client program that uses the exported API?
at line 4, you can see that the import statement saying
es “module1/pkg/elasticsearch”
it’s saying that we are importing the “es” package from “pkg/elasticsearch” directory of “module1”.
Here, the concept of “module” comes in. But let’s just talk about the import first. You can see that an alias “es” here. That’s the right package name we are importing. Because the New() func is contained in that “es” package.
But the story differs for “kafka” package
This is where the kafka package directory is located
pkg/kafka
└── consumer.go
and the consumer.go’s code looks like this
but when we did the import in the client program, the statement didn’t use any alias like this
“module1/pkg/kafka”
because the import directory path is just the same as package name.
So, what’s the module then?
so far, we’ve been playing with “pkg” directory.
.
├── cmd
├── go.mod
└── pkg
but on the same level, there is a file go.mod in Go application project.
The go.mod file is initialized with commmand
This way, we can create a module in a project. and the go.mod file is used for managing dependency and go version.
when the go.mod file is created, it looks like this when there are no 3rd party dependencies.
But once we add some dependency, for example, go-elasticsearch it’s going to list up the dependencies like this
So the bottomline is, we organize code into packages which belong to a module.