This is a template for writing a micro-service in go with a server infrastructure. It uses grpc-gateway
for endpoints which supports both GRPC & REST interfaces.
All the packages are loosely coupled so just remove them if not required. Make sure to clean imported infra packages from main.go if not used.
proto
- Proto definitions for your service. (e.g.)user.proto file defines your service interfaces.
- This service supports swagger UI. Make sure you change the
yourservice.swagger.json
within inproto/openapi/index.html
dtos
- Repository models, command structs to communicate between components.
services
- Application files to service the request
repository
- Optional if you access database
conf
- default.yml which used by default. main.go supports custom config file path.
Every component file within this service will have four functions
init
register your component structure with server to initialize the component with priority or to start your background services.
func init() {
server.RegisterService(&userRepo{}, server.Low)
}
Init
function where you intialize your component, register your services with bus for serving other components
func (c *userRepo) Init() (err error) {
c.addUserMigrations()
//Register for all the repository requests
bus.AddHandler(CreateUser)
bus.AddHandler(ListUsers)
return nil
}
Run
(optional)background service.<-ctx.Done()
will return err when server recieves termination, use this for safe shutdown.
func (c *GRPC) Run(ctx context.Context) error {
go func() {
<-ctx.Done()
log.Infoln("Stopping Grpc")
c.grpcServer.GracefulStop()
}()
log.WithField("Port", c.grpcPort).Info("Grpc listening...")
return c.grpcServer.Serve(c.listener)
}
OnConfig
called when config file is edited
func (service *UserService) OnConfig() {
}
bus
- Use bus to communicate between components, avoid circular imports
cache
- Three cache libraries are supported. Use the ones you need and remove others.
db
- Supports postgres incremental migration with
gorm
- Supports postgres incremental migration with
gateway
grpc-gateway
wrappers.
- Generate stubs using
buf
- Buf is a tool that provides various protobuf utilities such as linting, breaking change detection and generation. Please find installation instructions on https://docs.buf.build/installation/.
-
Run
make setup
installs all the modules requiredmake generate
compiles the proto filesgo run .
-
Deploy in
docker
docker-compose up -d