Skip to content

dokuzsertkol/dokuzsozluk

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

62 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

dokuzsozluk - Advanced Forum Backend in Go

Go Version PostgreSQL License

dokuzsozluk is currently under development. Features and structure may change in future versions.

A RESTful API backend for a collaborative forum platform. This project enables users to create categories, propose topics, write entries with voting mechanisms, and manage contributor roles and permissions.

Live Demo URL:

Live Demo Credentials:

  • Admin: admin / adminAdmin123*
  • User: user / UserUser123*
  • Restricted: restricted / restrictedRestricted123*
  • Banned: banned / bannedBanned123*

📋 Table of Contents


Features

User Management

  • User registration and authentication with JWT tokens
  • Role-based access control (Admin, User, Restricted, Banned)
  • Refresh token rotation for enhanced security
  • User profiles with unique slugs
  • Activity tracking (created_at, updated_at)

Content Management

  • Categories: Hierarchical organization of topics
  • Topics: Subject areas created within categories
  • Entries: Full article/contribution system for topics
  • Content versioning with author tracking
  • Soft deletion support

Voting System

  • Vote on entries (upvote/downvote concept)
  • Vote count tracking per entry
  • Prevent duplicate votes from same user
  • Vote statistics in responses

Search & Discovery

  • Full-text search across topics, entries, users, and categories
  • Pagination and sorting support
  • Query filtering and ordering (ascending/descending)
  • User-specific content listings

Role-Based Permissions

  • Admin Role: Full system access, user management
  • User Role: Standard contribution privileges
  • Restricted Role: Limited access (read-only or limited creation)
  • Banned Role: Revoked access
  • Granular permission system for category and content creation/updates

Security

  • JWT-based authentication with configurable expiration
  • Refresh token validation and rotation
  • CORS support for frontend integration
  • Rate limiting (IP-based and user-based hybrid approach)
  • Password hashing with bcrypt
  • Bearer token authentication in headers

API Features

  • Swagger/OpenAPI documentation with interactive UI
  • Comprehensive error handling with structured responses
  • Request validation with Go Playground validator
  • Pagination for large datasets
  • RESTful endpoint design

Tech Stack

Backend

  • Language: Go 1.25.5
  • Framework: Gorilla/mux (HTTP router)
  • Database: PostgreSQL 14+
  • ORM/Query Builder: Database/sql with custom queries
  • Authentication: JWT (golang-jwt/jwt)
  • Password Hashing: golang.org/x/crypto (bcrypt)
  • Validation: go-playground/validator

DevOps & Tools

  • Migration Tool: golang-migrate/migrate
  • API Documentation: Swaggo (Swagger/OpenAPI)
  • Configuration: godotenv (environment variables)
  • CORS: rs/cors
  • UUID Generation: google/uuid

Database

  • Primary DBMS: PostgreSQL
  • Driver: lib/pq
  • Migrations: SQL-based schema management

Architecture

The project follows a layered hexagonal architecture pattern:

cmd/
├── api/
│   └── main.go                 # Entry point
│
internal/
├── bootstrap/
│   └── server.go               # Server initialization
│
├── domain/                      # Business entities
│   ├── user/
│   ├── category/
│   ├── topic/
│   ├── entry/
│   ├── entryvote/
│   ├── rolepermission/
│   ├── refreshtoken/
│   └── shared/
│
├── usecase/                     # Business logic
│   ├── auth/
│   ├── user/
│   ├── category/
│   ├── topic/
│   ├── entry/
│   ├── entryvote/
│   ├── health/
│   └── ...
│
└── infrastructure/              # Technical implementation
    ├── config/                  # Configuration management
    ├── database/                # Database connections
    ├── router/                  # HTTP routing
    ├── middleware/              # HTTP middleware
    └── repository/              # Data access layer

Design Patterns

  • Repository Pattern: Abstract data access
  • Use Case Pattern: Business logic encapsulation
  • Dependency Injection: Loose coupling via constructors
  • Middleware Chain: Cross-cutting concerns (auth, validation, CORS)

Prerequisites

System Requirements

  • Go: 1.25.5 or higher
  • PostgreSQL: 14 or higher
  • Git: For version control

Installation Requirements

  • PostgreSQL server running and accessible
  • Go modules support enabled
  • Port 8080 available (configurable)

Installation & Setup

1. Clone the Repository

git clone https://github.com/dokuzsertkol/dokuzsozluk.git
cd dokuzsozluk

2. Install Dependencies

go mod download
go mod tidy

3. Install Migration Tool

go install -tags 'postgres' github.com/golang-migrate/migrate/v4/cmd/migrate@latest

4. Set Up Environment

Copy the .env.example file to .env and configure:

cp .env.example .env

Configuration

Environment Variables

Create a .env file in the project root with the following variables:

# Database Configuration
DB_URL=postgres://username:password@localhost:5432/dokuzsozluk?sslmode=disable
DB_USER=username
DB_PASS=password
DB_NAME=dokuzsozluk
DB_HOST=localhost
DB_PORT=5432

# Server Configuration
PORT=8080

# JWT Configuration
JWT_SECRET=your-super-secret-jwt-key-minimum-64-characters
JWT_EXPIRATION_MINS=15
REFRESH_SECRET=your-super-secret-refresh-key-minimum-64-characters
REFRESH_EXPIRATION_DAYS=7
REFRESH_EXPIRATION_DAYS_SHORT=1

# CORS Configuration
FRONTEND_URL=http://localhost:3000

# Rate Limiting
RATE_LIMIT_RATE=1
RATE_LIMIT_BURST=30

# API Documentation
SWAGGER_ENABLED=true

Configuration Details

Variable Description Default Example
DB_URL Full PostgreSQL connection string - postgres://user:pass@localhost:5432/dokuzsozluk
PORT Server port 8080 8080
JWT_EXPIRATION_MINS Access token expiration (minutes) 15 15
REFRESH_EXPIRATION_DAYS Refresh token expiration (days) 7 7
RATE_LIMIT_RATE Rate limit requests per second 1 1
RATE_LIMIT_BURST Rate limit burst size 30 30
SWAGGER_ENABLED Enable Swagger UI true true/false

Running the Application

1. Create PostgreSQL Database

psql -U postgres
CREATE DATABASE dokuzsozluk;
\q

2. Run Database Migrations

go run cmd/migrate/main.go

3. Start the Server

go run cmd/api/main.go

The server will start on http://localhost:8080 (configurable via PORT env var).

4. Verify Installation

curl http://localhost:8080/api/health

Expected response:

{
  "status": "OK",
  "timestamp": "2026-04-10T12:00:00Z"
}

API Documentation

Access Swagger UI

  • URL: http://localhost:8080/swagger/index.html
  • Requires SWAGGER_ENABLED=true in .env
  • Interactive API testing interface
  • Auto-generated from code annotations

Base URL

http://localhost:8080/api

Authentication

All protected endpoints require a Bearer token in the Authorization header:

Authorization: Bearer <access_token>

Core Endpoints

Authentication

  • POST /auth/login - Authenticate user, returns access & refresh tokens
  • POST /auth/logout - Revoke refresh token
  • POST /auth/refresh - Get new access token using refresh token
  • POST /auth/register - Create new user

Users

  • GET /users - List all users (with search, pagination, sorting)
  • GET /users/{slug} - Get user by slug
  • GET /users/me - Get authed user details
  • GET /users/{slug}/entries - Get entries by user
  • GET /users/{slug}/topics - Get topics by user
  • PATCH /users/{id} - Update user profile (requires permission)
  • PATCH /users/me - Update authed user profile (requires permission)

Categories

  • GET /categories - List categories (searchable, paginated)
  • GET /categories/{slug} - Get category by slug
  • POST /categories - Create new category (requires permission)
  • PATCH /categories/{id} - Update category (requires permission)

Topics

  • GET /topics - List all topics (searchable, paginated, sortable)
  • GET /topics/{slug} - Get topic by slug
  • POST /topics - Create new topic (requires permission)
  • PATCH /topics/{id} - Update topic (requires permission)

Entries

  • POST /topics/{topicID}/entries - Create new entry to an existing topic (requires permission)
  • PATCH /entries/{id} - Update entry (requires permission)

Entry Votes

  • POST /entries/{entryId}/vote - Vote on an entry

Health

  • GET /health - System health check

Core Entities

User

id           UUID PRIMARY KEY
username     VARCHAR(30) UNIQUE NOT NULL
email        VARCHAR(255) UNIQUE NOT NULL
password_hash VARCHAR(255) NOT NULL
avatar_url   VARCHAR(512) NOT NULL DEFAULT ''
bio          TEXT NOT NULL DEFAULT ''
score        INTEGER NOT NULL DEFAULT 0
entry_count  INTEGER NOT NULL DEFAULT 0
is_online    BOOLEAN NOT NULL DEFAULT false
role_id      INTEGER FOREIGN KEY -> roles.id
slug         TEXT
created_at   TIMESTAMPTZ NOT NULL
updated_at   TIMESTAMPTZ
deleted_at   TIMESTAMPTZ

Category

id           INTEGER PRIMARY KEY
title        VARCHAR(50) UNIQUE NOT NULL
description  VARCHAR(255) NOT NULL
sort_order   SMALLINT NOT NULL DEFAULT 1
slug         TEXT
created_at   TIMESTAMPTZ NOT NULL DEFAULT now()
updated_at   TIMESTAMPTZ
deleted_at   TIMESTAMPTZ

Topic

id           INTEGER PRIMARY KEY
title        VARCHAR(50) UNIQUE NOT NULL
category_id  INTEGER FOREIGN KEY -> categories.id
author_id    UUID FOREIGN KEY -> users.id (nullable)
slug         TEXT
created_at   TIMESTAMPTZ NOT NULL DEFAULT now()
updated_at   TIMESTAMPTZ
deleted_at   TIMESTAMPTZ

Entry

id           INTEGER PRIMARY KEY
content      TEXT NOT NULL
author_id    UUID FOREIGN KEY -> users.id
topic_id     INTEGER FOREIGN KEY -> topics.id
parent_id    INTEGER FOREIGN KEY -> entries.id (nullable)
upvote_count   INTEGER NOT NULL DEFAULT 0
downvote_count INTEGER NOT NULL DEFAULT 0
created_at   TIMESTAMPTZ NOT NULL DEFAULT now()
updated_at   TIMESTAMPTZ
deleted_at   TIMESTAMPTZ

EntryVote

id         INTEGER PRIMARY KEY
entry_id   INTEGER FOREIGN KEY -> entries.id
user_id    UUID FOREIGN KEY -> users.id
vote       SMALLINT NOT NULL  (1 or -1)

UNIQUE(entry_id, user_id)

Role

id   INTEGER PRIMARY KEY
name VARCHAR(30) UNIQUE NOT NULL

Permission

id   INTEGER PRIMARY KEY
name VARCHAR(30) UNIQUE NOT NULL

RolePermission

role_id       INTEGER FOREIGN KEY -> roles.id
permission_id INTEGER FOREIGN KEY -> permissions.id

PRIMARY KEY (role_id, permission_id)

RefreshToken

id          UUID PRIMARY KEY
user_id     UUID FOREIGN KEY -> users.id ON DELETE CASCADE
token_hash  TEXT NOT NULL
expires_at  TIMESTAMPTZ NOT NULL
created_at  TIMESTAMPTZ NOT NULL
revoked_at  TIMESTAMPTZ

Authentication & Authorization

JWT Flow

  1. Login: User submits credentials
  2. Token Generation: Server returns access token (15 mins) + refresh token (7 days)
  3. Token Usage: Client includes access token in Authorization header
  4. Token Refresh: When access token expires, use refresh token to get new access token
  5. Logout: Refresh token is revoked in database

Role-Based Access Control (RBAC)

Roles

Role Description Capabilities
Admin Full system access Manage users, categories, topics, and entries
User Standard contributor Create topics, write entries, vote
Restricted Limited access Read-only or restricted creation
Banned No access Account locked

Permissions

Permissions are linked to roles and define what actions can be performed on resources:

  • CATEGORY_CREATE - Create new categories
  • CATEGORY_UPDATE - Update categories
  • CATEGORY_DELETE - Delete categories
  • TOPIC_CREATE - Create new topics
  • TOPIC_UPDATE - Update topics
  • ENTRY_CREATE - Create new entries
  • ENTRY_UPDATE - Update entries
  • USER_MANAGE - Manage users
  • VIEW_ALL - View all content

Making Authenticated Requests

# Get access token
curl -X POST http://localhost:8080/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username":"user","password":"UserUser123*"}'

# Response includes tokens
# {
#   "access_token": "eyJ0eXAiOiJKV1QiLCJhbGc...",
#   "refresh_token": "eyJ0eXAiOiJKV1QiLCJhbGc...",
#   "token_type": "Bearer",
#   "expires_in": 900
# }

# Use access token in subsequent requests
curl http://localhost:8080/api/users \
  -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGc..."

Database Schema

Key Tables & Relationships

┌──────────────────┐
│      users       │
├──────────────────┤
│ id (PK)          │
│ username (UQ)    │
│ email (UQ)       │
│ role_id (FK)     │◉──────┐
└──────────────────┘       │
                           │
┌──────────────────┐       │
│      roles       │◄──────┘
├──────────────────┤
│ id (PK)          │
│ name (UQ)        │
└──────────────────┘


┌──────────────────┐
│   categories     │
├──────────────────┤
│ id (PK)          │
│ name             │
│ slug (UQ)        │
│ created_by (FK)  │────┐
└──────────────────┘    │
           ▲           │
           │           │
           │ (FK)      │
┌──────────────────┐    │
│     topics       │    │
├──────────────────┤    │
│ id (PK)          │    │
│ category_id (FK) │◄───┘
│ author_id (FK)   │────┐
││ slug (UQ)        │    │
└──────────────────┘    │
           ▲            │
           │            │
           │            │
┌──────────────────┐   │
│     entries      │   │
├──────────────────┤   │
│ id (PK)          │   │
│ topic_id (FK)    │◄──┘
│ author_id (FK)   │────┐
│ vote_count       │    │
└──────────────────┘    │
           ▲            │
           │            │
           │            │
┌──────────────────┐   │
│   entry_votes    │   │
├──────────────────┤   │
│ id (PK)          │   │
│ entry_id (FK)    │◄──┘
│ user_id (FK)     │────────┐
│ vote             │        │
└──────────────────┘        │
                            │
                    ┌────────┴──────┐
                    │               │
                 (back to users)    │
                                   │
                    ┌──────────────┘
                    │
┌──────────────────┐│
│ role_permissions│
├──────────────────┤
│ id (PK)          │
│ role_id (FK)     │
│ permission       │
│ resource         │
│ action           │
└──────────────────┘

Database Indexes

For optimized queries:

  • users: username, email, slug
  • topics: category_id, author_id, slug
  • entries: topic_id, author_id
  • entry_votes: entry_id, user_id (unique composite)

Development

Build the Project

go build -o bin/dokuzsozluk cmd/api/main.go

Run Tests (when available)

go test ./...

Code Organization

  • cmd/: Executable entry points
  • internal/domain/: Business entity definitions and interfaces
  • internal/usecase/: Business logic and workflows
  • internal/infrastructure/: Technical implementation details
  • migrations/: Database schema changes

Adding a New Feature

  1. Define domain entities in internal/domain/
  2. Create interfaces for data access
  3. Implement business logic in internal/usecase/
  4. Add repository implementations in internal/infrastructure/repository/
  5. Create HTTP handlers in internal/infrastructure/router/
  6. Add database migrations in migrations/
  7. Update Swagger documentation in handler comments

Dependencies Management

# Add a new dependency
go get github.com/package/name

# Update a dependency
go get -u github.com/package/name

# Clean up unused dependencies
go mod tidy

Contributing

Prerequisites for Contributors

  1. Fork the repository
  2. Clone your fork locally
  3. Create a feature branch: git checkout -b feature/your-feature-name
  4. Install dependencies: go mod download

Development Workflow

  1. Write Code: Make your changes following Go conventions
  2. Test Locally: Run migrations and test endpoints
  3. Update Docs: Update Swagger comments if API changes
  4. Commit: Use clear, descriptive commit messages
    git commit -m "feat: add new voting system"
    git commit -m "fix: correct user authentication flow"
    
  5. Push: Push to your fork
    git push origin feature/your-feature-name
    
  6. Pull Request: Create PR with:
    • Clear title and description
    • Reference to any related issues
    • Screenshots/examples if applicable

Code Style

  • Follow standard Go conventions (gofmt, golint)
  • Use meaningful variable and function names
  • Add comments for exported functions and complex logic
  • Keep functions focused and concise

Key Files

  • .env - Environment configuration (excluded from git)
  • migrations/ - Database schema
  • internal/ - Core application code
  • cmd/api/main.go - Application entry point

License

This project is licensed under the GNU General Public License v3.0 - see the LICENSE file for details.


Issues & Support

Found a bug? Have a feature request? Please create an issue on GitHub: Create Issue


Contact & References

  • Project: dokuzsozluk - Advanced Forum Backend in Go
  • GitHub: dokuzsertkol/dokuzsozluk
  • Language: Go 1.25.5
  • Database: PostgreSQL 14+

Additional Resources


Last Updated: April 10, 2026

About

[Under Development] Advanced Forum Backend in Go. Includes a category–topic–entry architecture along with JWT authentication, rate limiting, role-based access control, refresh token and CORS handling support.

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors