Skip to content
prateekcodePublic

About

Learning project: blog REST API in Go with PostgreSQL (GORM), gorilla/mux and JWT authentication.

Topics

Resources

Stars

0 stars

Watchers

2 watching

Forks

Latest commit

 

History

3 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

BlogApp

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.

Stack

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

Architecture

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"]
Loading
.
├── 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.

Authentication

  • POST /login checks the email and bcrypt password hash and returns a signed HS256 JWT with claims authorized, user_id and exp (1 hour).
  • The signing key comes from the API_SECRET environment 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 BeforeSave hook before they're stored.

API

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}'

Configuration

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-me

The app stops at startup if .env is missing. Only the postgres driver is supported.

Running locally

# 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.Load drops the users and posts tables, migrates them again and inserts two sample users and posts (see api/seed/seeder.go). Point it only at a throwaway database.

Tests

There are no automated tests in this repository yet.

Known limitations

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 by golang-jwt/jwt) and GORM v1. go.mod also lists unused dependencies (gofiber/fiber).
  • sslmode=disable is hard-coded for the database connection, and the port is fixed at :8080.
  • The User model serialises its password field, so user responses (including posts' author) contain the bcrypt hash.
  • No pagination, rate limiting or refresh tokens.
  • SignIn only returns an error on a bcrypt mismatch, so other password-check errors aren't handled.

About

Learning project: blog REST API in Go with PostgreSQL (GORM), gorilla/mux and JWT authentication.

Topics

Resources

Stars

0 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages