From b0c40d8ade3207f163a4acc99efc0e27105d678b Mon Sep 17 00:00:00 2001 From: Wilfried OLLIVIER Date: Sat, 28 Mar 2020 11:52:07 +0100 Subject: [PATCH] Add go packages --- src/SUMMARY.md | 1 + src/dev/golang/packages.md | 68 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 src/dev/golang/packages.md diff --git a/src/SUMMARY.md b/src/SUMMARY.md index bf33565..4cbfe42 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -5,6 +5,7 @@ - [Dev](./dev/main.md) - [Golang](./dev/golang/main.md) + - [Packages](./dev/golang/packages.md) - [Testing](./dev/golang/testing.md) - [Elixir](./dev/elixir/main.md) - [Lambda](./dev/elixir/lambda.md) diff --git a/src/dev/golang/packages.md b/src/dev/golang/packages.md new file mode 100644 index 0000000..6b3681a --- /dev/null +++ b/src/dev/golang/packages.md @@ -0,0 +1,68 @@ +# 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 : + +```txt +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 + +```shell +go mod init github.com/username/project +``` + +### Add an external dep to your project + +Import the required package + +```go +import "github.com/example/lib" +``` + +The next time you will run a go command it will fetch the package, eg : + +```shell +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, + +```shell +mkdir -p pkg/foo && echo "package foo" > pkg/foo/foo.go +``` + +After adding stuff in your `foo.go` file, import it using + +```go +import "github.com/username/project/foo" +```