A REST API for a simple blog, written in Go with PostgreSQL. Users can register and log in with a JWT, and authors create, edit and delete their own posts.
Status: a 2022 learning project for Go web services: routing, an ORM, password hashing and token auth. It isn't production-ready. See Known limitations.
| Language | Go 1.17 |
| HTTP router | gorilla/mux on net/http |
| Database | PostgreSQL through GORM v1 (jinzhu/gorm) |
| Auth | dgrijalva/jwt-go (HS256), passwords hashed with bcrypt |
| Validation | badoux/checkmail for email format |
| Config | .env loaded with joho/godotenv |
flowchart LR
C["HTTP client"] --> R["gorilla/mux router<br/>controller/routes.go"]
R --> MW["middlewares<br/>JSON headers · JWT check"]
MW --> H["controller handlers<br/>users · posts · login"]
H --> M["models<br/>User · Post (GORM)"]
M --> DB[("PostgreSQL")]
H --> A["auth<br/>create / parse JWT"]
.
├── main.go entry point → api.Run()
└── api/
├── server.go loads .env, connects DB, seeds, listens on :8080
├── controller/ Server struct, routes, HTTP handlers
├── middlewares/ SetMiddlewareJSON, SetMiddlewareAuthentication
├── auth/ CreateToken, TokenValid, ExtractToken, ExtractTokenID
├── models/ User and Post: validation + GORM queries
├── responses/ JSON and ERROR response helpers
├── seed/ drops, migrates and seeds the tables at startup
└── utils/formaterror/ maps DB errors to user-facing messages
Request flow. Routes are registered in controller/routes.go. Each handler is wrapped in SetMiddlewareJSON, and write operations on existing resources are also wrapped in SetMiddlewareAuthentication, which rejects requests without a valid token. Inside the handler, auth.ExtractTokenID reads the user id from the token and compares it with the resource owner before any update or delete.
POST /loginchecks the email and bcrypt password hash and returns a signed HS256 JWT with claimsauthorized,user_idandexp(1 hour).- The signing key comes from the
API_SECRETenvironment variable. - Send the token as
Authorization: Bearer <token>. A?token=query parameter is also accepted. - The token parser rejects tokens that aren't signed with HMAC.
- Passwords are hashed with bcrypt in a GORM
BeforeSavehook before they're stored.
All responses are JSON. The server listens on :8080.
| Method | Path | Auth | Description |
|---|---|---|---|
GET |
/ |
Health/welcome message | |
POST |
/login |
Log in, returns a JWT | |
POST |
/users |
Register a user (nickname, email, password) |
|
GET |
/users |
List users | |
GET |
/users/{id} |
Get one user | |
PUT |
/users/{id} |
✓ | Update your own user |
DELETE |
/users/{id} |
✓ | Delete your own user |
POST |
/posts |
✓* | Create a post (title, content, author_id) |
GET |
/posts |
List posts with their authors | |
GET |
/posts/{id} |
Get one post | |
PUT |
/posts/{id} |
✓ | Update your own post |
DELETE |
/posts/{id} |
✓ | Delete your own post |
* POST /posts isn't wrapped in the auth middleware, but the handler requires a valid token and checks that author_id matches the token's user.
Example:
# log in with a seeded user
curl -s -X POST localhost:8080/login \
-H 'Content-Type: application/json' \
-d '{"email":"<seeded email>","password":"<seeded password>"}'
# create a post
curl -s -X POST localhost:8080/posts \
-H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' \
-d '{"title":"Hello","content":"First post","author_id":1}'Create a .env file in the project root (it's already in .gitignore):
DB_DRIVER=postgres
DB_HOST=127.0.0.1
DB_PORT=5432
DB_USER=postgres
DB_PASSWORD=postgres
DB_NAME=blogapp
API_SECRET=change-meThe app stops at startup if .env is missing. Only the postgres driver is supported.
# Postgres in Docker (or use a local install)
docker run --name blogapp-db -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=blogapp -p 5432:5432 -d postgres
go run .
⚠️ On every start,seed.Loaddrops theusersandpoststables, migrates them again and inserts two sample users and posts (seeapi/seed/seeder.go). Point it only at a throwaway database.
There are no automated tests in this repository yet.
These are known gaps, listed so nobody mistakes this project for production code:
- Data is reset on every start by the seeder.
- No test suite, no CI.
- Uses unmaintained libraries:
dgrijalva/jwt-go(succeeded bygolang-jwt/jwt) and GORM v1.go.modalso lists unused dependencies (gofiber/fiber). sslmode=disableis hard-coded for the database connection, and the port is fixed at:8080.- The
Usermodel serialises itspasswordfield, so user responses (including posts'author) contain the bcrypt hash. - No pagination, rate limiting or refresh tokens.
SignInonly returns an error on a bcrypt mismatch, so other password-check errors aren't handled.