This is my goto template for creating a new API in Go. It includes a basic structure for the project, logging, configuration, and database setup. It's a slimmed down version of the template we use for our Go services at my job with some changes for new libraries or patterns I prefer.
- Clone the repo to a directory with your project name
- Update
go.modfile with your project name - Update
docker-compose.ymlfile with your project name in the relevant places (DB name, app name, etc) - Update module name in
.mockery.ymlto match your project name - Update variables in the Makefile to match your project name ($PROJNAME and $DB_CONNECTION_URI for example)
- Rename
.env-templateto.envand set appropriate values - The template sets up Users as an example in domain, service, and data directories. Update or delete as you see fit. Delete the migrations and start new ones
- Go build something cool!
- Router - Chi
- Logging - Zerolog
- .ENV file support - godotenv
- Reading config into structs - cleanenv
- DB extensions - SQLX
- DB migrations - go-migrate
- Mocking - mockery
- Testify - testify
- chi's RequestID - adds a request ID to the context
- chi's RealIP - adds the real IP to the context
- custom RequestResponseLogger - logs the request and response. Also adds requestID to each log entry for correlating logs
- chi's Heartbeat - adds a /ping endpoint to check if the server is up
- custom Recoverer - recovers from panics and logs the error. Custom so that error is logged with requestID as well as message and string stack trace to make alerting on and viewing in log aggregators easier
- chi's Compress - compresses the response
- chi's Timeout - adds a timeout to the request context