Small Go HTTP API demonstrating a minimal service structure using chi router, middleware, and a mock database.
- Module: github.com/jetqin/goapi
- Entry:
cmd/api/main.go - Router:
github.com/go-chi/chi - Logger:
github.com/sirupsen/logrus - ASCII banner printed with
github.com/common-nighthawk/go-figure - Mock database in
internal/tools/mockdb.go
cmd/api/main.go— application entrypoint; sets up router and prints banner.api/api.go— small HTTP response helpers and error types.internal/handlers/— HTTP handlers (e.g.GetCoinBalance).internal/middleware/— middleware (authorization, logger).internal/tools/— mock database and supporting types.
- Handlers register routes via
handlers.RegisterHandlers(r). - Middleware chain includes request logging and an authorization check that validates
username(query) andAuthorizationheader. tools.NewDatabaseInterface()returns a mockDatabaseInterfacebacked bymockDBimplemented ininternal/tools/mockdb.go.
- Ensure dependencies are present (Go >= 1.25 recommended):
cd /path/to/goapi
go get ./...- Run the server:
go run cmd/api/main.go- Example request (valid credentials present in mock data):
curl -i 'http://localhost:8080/account/coins?username=alex' -H 'Authorization:123ABC'Expected JSON response:
{"Code":200,"Balance":100}- GET /account/coins?username={username}
- Headers:
Authorization: <token> - Success: 200 with
CoinBalanceResponseJSON - Errors: 400/500 with
ErrorJSON
- Headers:
- Address already in use: another process is listening on port 8080. Find and kill it, or change the port.
- macOS example:
lsof -i :8080 -sTCP:LISTENthenkill <PID>
- macOS example:
- Wrong path: the current handler uses
/account/coins(plural). If you hit/account/coinyou'll get 404. - Missing header/query: Authorization header and
usernamequery must be present. The middleware returns 400 for missing/invalid credentials. - Dependencies: run
go getto ensure third-party modules are installed.
- The project uses an in-memory mock DB for demo; swap
mockDBfor a real DB client by implementingDatabaseInterface. - Consider adding an alias route for
/account/coinif backward compatibility is required. - Add unit tests for handlers and middleware.
For further changes, update the handlers in internal/handlers or the mock data in internal/tools/mockdb.go.