A blogging backend written with the aim to learn Golang basics, how to best structure things in it, basic CRUD API building and learning mysql (above the usual queries).
- Golang is easy to learn and use.
- It’s better to keep data layer separate since packages will need to call each other. Due to golang structure, they want each package to be self sufficient, making interfaces for each package and maintaining it becomes quite cumbersome.
- Hate that it's missing optional parameters in functions, repetitive error handling, necessary parenthesis even with single lines, overloading functions.
The code is divided into following packages and files:
- Commons
- To hold stuff common for other packages - logging, validators, input sanitizers, utils, error handling etc.
- Depends on no other package
- Data layer
- Holds the DB Data models, DAO’s to access them and useful API entities
- Depends on commons package
- Endpoints
- Sub-packages for user, comment & replies, like and articles endpoints
- Each sub-package holds a handler.go to register different endpoints and their respective handlers in the sub router along with any custom config for security, timeout etc.
- Depends on commons & data layer packages
- Middlewares
- Holds all the middlewares - common model (access token, user id) , security, request and response logging, timeout
- Depends on commons and data layer packages
- main.go
- The entry point to this monolith
- config.json
- Holds the configuration for database and server
Each API in the crud is divided into 3 files
- models.go
- Holds RequestModel
- The model has necessary fields for the operation (e.g. article id, common model etc.)
- Input validation struct tags using go-validator for ids, email, string length, password etc.
- Sanitising input using Bluemonday for prevention against XSS attacks
- ResponseModel
- The model that will be sent back as json result for the API
- Json tags for marshalling
- Holds RequestModel
- handler.go
- Handles the incoming request and transforms it into the request model
- Checks for Authorization and security checks (permissions, id existing etc.) and provides model to action.go
- Makes a sub-logger from the default logger library for structured logging (i.e. adds certain relevant field to each API)
- action.go
- Handles the actual actions executing business logic
- Uses one or more DAO’s for the db tasks
- Handles db tasks using transaction where necessary
- Uses the sub-logger from its handler.go to log steps that were completed or failed with relevant message.