Organising go micro functions ...
Go is an amazing language for writing distributed microservices or micro- programs/functions that will do a single job at a time. I am in love with a single binary file for each function and its easy deployment as a person from a JS world background.
I recently started using a simple but productive structure for the apps that I build,
and the same structure to build cloud functions as well.
bin/
functions/
x
main.go
type.go
db.go
y
main.go
type.go
db.go
common
common.go
response.go
models
models.go
migrator
main.go
Makefile
go.sum
go.mod
Here x and y are two functions ( folder name is considered as function name), and also both are mutually exclusive
Each function will have its own DB connection, but models will be shared as making model as a package models
and common files also can be shared as a separate package inside.
The Migrator program will sync DB schemas to the DB. I prefer gorm
as ORM layer.
To make build easy,
functions := $(shell find functions -name \*main.go | awk -F'/' '{print $$2}')
build: ## Build each functions one by one and move to bin folder
$(info Starting Build....)
@for function in $(functions) ; do \
env go build -ldflags="-s -w" -o bin/$$function functions/$$function/*.go ; \
done
$(info Build Completed. Time to deploy!)
migrate:
go run migrator/*.go
run:
go run functions/x/*.go
make build
- loops through each function and it will build each function and outputs to bin folder function folder name as the function name.
using *.go for combining all go files in the folder to make binary.
Happy Hacking 🖖