> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/go-gitea/gitea/llms.txt
> Use this file to discover all available pages before exploring further.

# Architecture Overview

> Understanding Gitea's architecture and codebase structure

## Overview

Gitea is a full-stack web application built with Go on the backend and Vue.js on the frontend. It follows a modular, layered architecture that separates concerns and enables maintainability.

## Technology Stack

<CardGroup cols={2}>
  <Card title="Backend" icon="server">
    * **Language**: Go 1.26+
    * **Web Framework**: Chi router
    * **ORM**: XORM
    * **Template Engine**: Go templates
  </Card>

  <Card title="Frontend" icon="browser">
    * **Framework**: Vue.js 3.5+
    * **Build Tool**: Webpack 5
    * **Language**: TypeScript
    * **Styling**: CSS with Tailwind
  </Card>

  <Card title="Database" icon="database">
    * PostgreSQL (recommended)
    * MySQL / MariaDB
    * SQLite3
    * MSSQL
  </Card>

  <Card title="Storage" icon="hard-drive">
    * Local filesystem
    * S3-compatible (MinIO, AWS S3)
    * Azure Blob Storage
  </Card>
</CardGroup>

## Directory Structure

```
gitea/
├── cmd/                  # Command-line interface
│   ├── web.go           # Web server command
│   ├── admin.go         # Admin commands
│   └── ...
├── models/              # Database models and schemas
│   ├── user/            # User models
│   ├── repo/            # Repository models
│   ├── issues/          # Issue/PR models
│   └── ...
├── modules/             # Shared utility modules
│   ├── git/             # Git operations
│   ├── auth/            # Authentication
│   ├── setting/         # Configuration
│   └── ...
├── routers/             # HTTP request routing
│   ├── web/             # Web UI routes
│   ├── api/             # API routes
│   └── ...
├── services/            # Business logic layer
│   ├── repository/      # Repository services
│   ├── user/            # User services
│   ├── issue/           # Issue services
│   └── ...
├── templates/           # HTML templates
│   ├── repo/            # Repository pages
│   ├── user/            # User pages
│   └── ...
├── web_src/             # Frontend source code
│   ├── js/              # JavaScript/TypeScript
│   ├── css/             # Stylesheets
│   └── ...
├── public/              # Static assets (compiled)
├── options/             # Configuration templates
└── tests/               # Test suites
```

## Layered Architecture

Gitea follows a clean architecture with clear separation of concerns:

```mermaid theme={null}
graph TD
    A[HTTP Request] --> B[Routers]
    B --> C[Services]
    C --> D[Models]
    D --> E[Database]
    C --> F[Modules]
    F --> G[Git/External]
```

### Layer Responsibilities

<Steps>
  <Step title="Routers Layer">
    **Location**: `routers/web/`, `routers/api/`

    * Handle HTTP requests/responses
    * Parse request parameters
    * Validate input
    * Call service layer
    * Render responses (HTML or JSON)

    ```go theme={null}
    // Example router handler
    func CreateRepository(ctx *context.Context) {
        form := web.GetForm(ctx).(*forms.CreateRepoForm)
        repo, err := repo_service.CreateRepository(ctx, ctx.Doer, form.ToCreateRepoOption())
        if err != nil {
            ctx.Error(http.StatusInternalServerError)
            return
        }
        ctx.JSON(http.StatusCreated, convert.ToRepo(repo, permission.AccessModeOwner))
    }
    ```
  </Step>

  <Step title="Services Layer">
    **Location**: `services/`

    * Implement business logic
    * Orchestrate multiple operations
    * Handle transactions
    * Emit notifications/webhooks

    ```go theme={null}
    // Example service function
    func CreateRepository(ctx context.Context, doer *user_model.User, opts CreateRepoOptions) (*repo_model.Repository, error) {
        // Validate
        // Create repository record
        // Initialize git repository
        // Set up default branch
        // Trigger webhooks
        return repo, nil
    }
    ```
  </Step>

  <Step title="Models Layer">
    **Location**: `models/`

    * Define data structures
    * Database operations (CRUD)
    * Query builders
    * Migrations

    ```go theme={null}
    // Example model
    type Repository struct {
        ID          int64
        OwnerID     int64
        Name        string
        Description string
        IsPrivate   bool
        CreatedUnix timeutil.TimeStamp
    }

    func GetRepositoryByID(ctx context.Context, id int64) (*Repository, error) {
        repo := new(Repository)
        has, err := db.GetEngine(ctx).ID(id).Get(repo)
        if !has {
            return nil, ErrRepoNotExist{ID: id}
        }
        return repo, err
    }
    ```
  </Step>

  <Step title="Modules Layer">
    **Location**: `modules/`

    * Utility functions
    * External integrations
    * Git operations
    * Authentication providers
  </Step>
</Steps>

## Key Components

### Git Integration

Gitea interacts with Git repositories through:

* **Native Git**: Executes git commands via `modules/git/`
* **Git LFS**: Large file storage support
* **Git Hooks**: Server-side and client-side hooks

### Authentication System

Multiple authentication backends:

```go theme={null}
// modules/auth/
- LDAP (Bind DN and Simple Auth)
- OAuth2 (GitHub, GitLab, Google, etc.)
- SMTP
- PAM
- SSPI (Windows)
```

### Database Abstraction

XORM provides database-agnostic queries:

```go theme={null}
// Works across PostgreSQL, MySQL, SQLite, MSSQL
repos, err := db.Find(ctx, FindRepoOptions{
    OwnerID: userID,
    Private: false,
    Page:    1,
    PageSize: 20,
})
```

### Queue System

Asynchronous task processing:

```go theme={null}
// Background jobs
- Email notifications
- Webhook deliveries
- Repository mirroring
- Git garbage collection
```

## Request Flow

### Web Request Example

```
1. User visits /user/repo/issues/new
   ↓
2. Chi router matches route → routers/web/repo/issue.go
   ↓
3. Handler validates permissions (middleware)
   ↓
4. Handler calls services/issue/Create()
   ↓
5. Service creates issue in database (models/issues/)
   ↓
6. Service triggers notifications and webhooks
   ↓
7. Handler renders HTML template (templates/repo/issue/new.tmpl)
   ↓
8. Response sent to user
```

### API Request Example

```
1. POST /api/v1/repos/:owner/:repo/issues
   ↓
2. API router → routers/api/v1/repo/issue.go
   ↓
3. Authenticate token (middleware)
   ↓
4. Parse JSON request body
   ↓
5. Call services/issue/Create()
   ↓
6. Return JSON response
```

## Database Schema

Core database tables:

```sql theme={null}
-- Users and authentication
user, email_address, access_token, oauth2_application

-- Repositories
repository, release, branch, protected_branch

-- Collaboration
issue, pull_request, comment, review, milestone, label

-- Organizations
org_user, team, team_user, team_repo

-- Actions (CI/CD)
action_run, action_run_job, action_runner

-- Packages
package, package_version, package_file
```

## Middleware

Request middleware pipeline:

```go theme={null}
// Common middleware
- Context initialization
- Session management
- CSRF protection
- Authentication
- Permission checks
- Rate limiting
- Logging
```

## See Also

<CardGroup cols={2}>
  <Card title="Database Layer" href="/development/database">
    Deep dive into database architecture
  </Card>

  <Card title="Frontend" href="/development/frontend">
    Frontend architecture and build system
  </Card>

  <Card title="Contributing" href="/development/contributing">
    Learn how to contribute
  </Card>

  <Card title="Building" href="/development/building">
    Build Gitea from source
  </Card>
</CardGroup>
