Working with packages

In go, every project, is, at some part, a package.

A package is simply a directory containing go source file.

Organising projects

In your project, you may need multiple, isolated packages. Here is the most common project layout in found and I used in all my projects :

layout -- top project directory
├── build -- all things related to ci
│   └── ci
│       └── ci.yml
├── cmd -- main package, entrypoing
│   └── layout.go
├── Dockerfile -- container build instructions
├── init -- if usefull systemd service file
│   └── layout.service
├── internal -- private packages, ie not to be used in another project
│   └── private
│       └── private.go
├── LICENSE -- license file
├── pkg -- public packages, ie packages like libs, to be importer in another project
│   └── public
│       └── public.go
└── README.md -- readme

Using go mod

Init project

go mod init github.com/username/project

Add an external dep to your project

Import the required package

import "github.com/example/lib"

The next time you will run a go command it will fetch the package, eg :

go build

In repository packages

Of course, you can also use isolated package you write inside your repository (usefull if you need to split things up)

Let's say, for example, I want to add a new public package foo in my project,

mkdir -p pkg/foo && echo "package foo" > pkg/foo/foo.go

After adding stuff in your foo.go file, import it using

import "github.com/username/project/foo"