mithril

module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 25, 2025 License: MIT

README ΒΆ

Mithril Framework

A batteries-included web framework built on Fiber v2 with Laravel/Django-inspired features including artisan-like CLI, GORM migrations, auto-generated Swagger documentation, module system, comprehensive auth, multi-database support, and production deployment tools.

πŸš€ Quick Start

Installation
# Automatic OS detection and installation
curl -fsSL https://raw.githubusercontent.com/mithril-framework/mithril/main/install.sh | sh

This single command automatically:

  • Detects your operating system (Linux, macOS, Windows)
  • Installs Mithril using the best method for your platform
  • Falls back to alternative methods if needed
  • Verifies the installation
Option 2: Manual Installation
# Install the global CLI manually
go install github.com/mithril-framework/mithril/cmd/mithril@latest
Create Your First Project
# Create a new project
mithril new myproject
cd myproject

# Install dependencies
go mod tidy

# Run the application
go run main.go
First Steps
  1. Configure your environment:

    cp .env.example .env
    # Edit .env with your database and other settings
    
  2. Run database migrations:

    go run . artisan migrate
    
  3. Start the development server:

    go run . artisan serve
    
  4. Visit your application:

πŸ“š Features

Core Framework
  • Fiber v2 - High-performance HTTP framework
  • GORM - Powerful ORM with migrations
  • Configuration Management - Environment-based config with validation
  • Dependency Injection - Laravel-style service container
  • Middleware Stack - CORS, CSRF, rate limiting, sessions, guards
CLI & Generators
  • Global CLI - mithril new project-name
  • Local Artisan - go run . artisan make:model User
  • Module Generator - Django-style app creation
  • Model Generator - Auto-generate models with relationships
  • Auth Scaffolding - Complete authentication system
Database & Migrations
  • Multi-database Support - PostgreSQL, MySQL, SQLite, MongoDB
  • Laravel-style Migrations - Up/Down methods with rollback
  • Seeders - Database seeding for development
  • Backup & Restore - Database backup utilities
  • UUID Primary Keys - Default UUID support
Authentication & Authorization
  • JWT Tokens - Access and refresh token management
  • Session Management - Database-backed sessions
  • 2FA Support - TOTP authenticator apps
  • Email Verification - Email verification system
  • Password Reset - Secure password reset flow
  • RBAC - Role-based access control
API Features
  • Request/Response Validation - FastAPI-style validation
  • Auto-generated Swagger - OpenAPI 3.0 documentation
  • Pagination - Built-in pagination support
  • Sorting - Multi-field sorting
  • Rate Limiting - Per IP, user, route rate limiting
File Storage
  • S3 Integration - AWS S3 support
  • MinIO Support - S3-compatible storage
  • Local Storage - Local file storage
  • File Upload/Download - Complete file management
  • Backup & Restore - File backup utilities
Background Jobs
  • Queue System - Memory, Redis, RabbitMQ, Kafka
  • Task Scheduling - Cron-like scheduling
  • Job Retries - Automatic retry with backoff
  • Dead Letter Queue - Failed job handling
Real-time Communication
  • WebSocket Support - Real-time communication
  • gRPC Support - High-performance RPC
  • Room/Channel Support - WebSocket rooms
Monitoring & Observability
  • Health Checks - /health, /livez, /readyz
  • Prometheus Metrics - /metrics endpoint
  • OpenTelemetry - Distributed tracing
  • Sentry Integration - Error tracking
  • Structured Logging - JSON logging
Development Tools
  • Live Reload - Air integration for development
  • Hot Reload - Configuration hot reloading
  • Test Suite - Comprehensive testing utilities
  • Code Generation - CLI generators for all components

πŸ—οΈ Project Structure

myproject/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ controllers/          # HTTP controllers
β”‚   β”œβ”€β”€ middleware/           # Custom middleware
β”‚   β”œβ”€β”€ models/              # GORM models
β”‚   β”œβ”€β”€ schemas/             # Request/response validation
β”‚   └── modules/             # Django-style modules
β”œβ”€β”€ config/                  # Configuration files
β”œβ”€β”€ database/
β”‚   β”œβ”€β”€ migrations/          # Database migrations
β”‚   └── seeders/            # Database seeders
β”œβ”€β”€ routes/
β”‚   β”œβ”€β”€ api.go              # API routes
β”‚   β”œβ”€β”€ web.go              # Web routes
β”‚   └── console.go          # Console commands
β”œβ”€β”€ templates/              # HTML templates
β”œβ”€β”€ utils/                  # Utility functions
β”œβ”€β”€ artisan                 # Local CLI script
β”œβ”€β”€ main.go                 # Application entry point
β”œβ”€β”€ Makefile               # Build automation
β”œβ”€β”€ Dockerfile             # Docker configuration
β”œβ”€β”€ docker-compose.*.yml   # Docker Compose files
└── .github/workflows/     # CI/CD pipelines

πŸ› οΈ CLI Commands

Project Management
# Create new project
mithril new myproject

# Create new module
go run . artisan make:module shop --full

# Create new model
go run . artisan make:model Product

# Create new controller
go run . artisan make:controller ProductController
Database Operations
# Run migrations
go run . artisan migrate

# Rollback migrations
go run . artisan migrate:rollback

# Create migration
go run . artisan make:migration create_products_table

# Create seeder
go run . artisan make:seeder ProductSeeder

# Run seeders
go run . artisan db:seed

# Backup database
go run . artisan db:backup

# Restore database
go run . artisan db:restore --file=backup.sql
Authentication
# Scaffold authentication
go run . artisan make:auth

# Create superuser
go run . artisan createsuperuser
Queue & Jobs
# Start queue worker
go run . artisan queue:work

# List failed jobs
go run . artisan queue:failed

# Retry failed job
go run . artisan queue:retry 1
Development
# Start development server
go run . artisan serve

# List all routes
go run . artisan routes:list

# Run tests
go test ./...

# Run with live reload
air

πŸ”§ Configuration

Mithril uses environment-based configuration with validation and default values.

Environment Variables
# Application
APP_NAME="My App"
APP_ENV="development"
APP_DEBUG="true"
APP_HOST="localhost"
APP_PORT="3000"

# Database
DB_DRIVER="postgres"
DB_HOST="localhost"
DB_PORT="5432"
DB_NAME="myapp"
DB_USER="myapp"
DB_PASSWORD="password"

# JWT
JWT_SECRET="your-jwt-secret-32-characters-long"
JWT_ACCESS_TOKEN_EXPIRY="15m"
JWT_REFRESH_TOKEN_EXPIRY="7d"

# Mail
MAIL_DRIVER="smtp"
MAIL_HOST="localhost"
MAIL_PORT="587"
MAIL_FROM_ADDRESS="noreply@example.com"

# Storage
STORAGE_DRIVER="s3"
S3_REGION="us-east-1"
S3_BUCKET="myapp-storage"
Configuration Files
// config/app.go
type AppConfig struct {
    Name        string `env:"APP_NAME" default:"Mithril App"`
    Environment string `env:"APP_ENV" default:"development"`
    Debug       bool   `env:"APP_DEBUG" default:"false"`
    Host        string `env:"APP_HOST" default:"localhost"`
    Port        int    `env:"APP_PORT" default:"3000"`
}

πŸ—„οΈ Database

Models
// app/models/user.go
type User struct {
    ID        uint      `json:"id" gorm:"primaryKey"`
    Email     string    `json:"email" gorm:"uniqueIndex"`
    Password  string    `json:"-"`
    Name      string    `json:"name"`
    CreatedAt time.Time `json:"created_at"`
    UpdatedAt time.Time `json:"updated_at"`
}
Migrations
// database/migrations/20240101000000_create_users_table.go
func (m *CreateUsersTable) Up(db *gorm.DB) error {
    return db.AutoMigrate(&User{})
}

func (m *CreateUsersTable) Down(db *gorm.DB) error {
    return db.Migrator().DropTable(&User{})
}
Seeders
// database/seeders/user_seeder.go
func (s *UserSeeder) Run(db *gorm.DB) error {
    users := []User{
        {Email: "admin@example.com", Name: "Admin User"},
        {Email: "user@example.com", Name: "Regular User"},
    }
    
    for _, user := range users {
        db.Create(&user)
    }
    
    return nil
}

πŸ” Authentication

JWT Configuration
// config/jwt.go
type JWTConfig struct {
    Secret             string        `env:"JWT_SECRET" required:"true"`
    AccessTokenExpiry  time.Duration `env:"JWT_ACCESS_TOKEN_EXPIRY" default:"15m"`
    RefreshTokenExpiry time.Duration `env:"JWT_REFRESH_TOKEN_EXPIRY" default:"7d"`
}
Auth Routes
// routes/api.go
app.Post("/auth/login", auth.Login)
app.Post("/auth/register", auth.Register)
app.Post("/auth/refresh", auth.Refresh)
app.Post("/auth/logout", auth.Logout)
app.Post("/auth/forgot-password", auth.ForgotPassword)
app.Post("/auth/reset-password", auth.ResetPassword)
Middleware
// app/middleware/auth.go
func AuthMiddleware() fiber.Handler {
    return func(c *fiber.Ctx) error {
        token := c.Get("Authorization")
        if token == "" {
            return c.Status(401).JSON(fiber.Map{"error": "Unauthorized"})
        }
        
        // Validate JWT token
        // ...
        
        return c.Next()
    }
}

πŸ“ API Documentation

Request Validation
// app/schemas/user_request.go
type CreateUserRequest struct {
    Email    string `json:"email" validate:"required,email" example:"user@example.com"`
    Password string `json:"password" validate:"required,min=8" example:"password123"`
    Name     string `json:"name" validate:"required" example:"John Doe"`
}

// app/controllers/user_controller.go
func CreateUser(c *fiber.Ctx) error {
    var req CreateUserRequest
    if err := c.BodyParser(&req); err != nil {
        return c.Status(400).JSON(fiber.Map{"error": err.Error()})
    }
    
    // Validate request
    if err := validate.Struct(req); err != nil {
        return c.Status(400).JSON(fiber.Map{"error": err.Error()})
    }
    
    // Create user
    // ...
}
Auto-generated Swagger

Visit /docs for Swagger UI or /redoc for ReDoc.

πŸ§ͺ Testing

Unit Tests
// pkg/config/config_test.go
func TestAppConfig_NewAppConfig(t *testing.T) {
    config := NewAppConfig()
    assert.NotNil(t, config)
    assert.Equal(t, "Mithril App", config.Name)
}
Integration Tests
// pkg/testing/integration_test.go
func TestIntegration_HTTPRequests(t *testing.T) {
    helper := NewTestHelper(t)
    defer helper.Cleanup()
    
    helper.SetupTestRoutes()
    
    resp := helper.Get(t, "/health")
    resp.AssertStatus(t, 200)
    resp.AssertJSON(t, map[string]string{"status": "ok"})
}
E2E Tests
// pkg/testing/e2e_test.go
func TestE2E_CompleteUserWorkflow(t *testing.T) {
    suite := NewE2ETestSuite(t)
    defer suite.Close()
    
    // Test complete user workflow
    // ...
}

πŸš€ Deployment

Docker
# Dockerfile
FROM golang:1.21-alpine AS builder
WORKDIR /app
COPY . .
RUN go mod download
RUN go build -o main .

FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /app/main .
COPY --from=builder /app/.env .
CMD ["./main"]
Docker Compose
# docker-compose.yml
version: '3.8'
services:
  app:
    build: .
    ports:
      - "3000:3000"
    environment:
      - DB_HOST=postgres
    depends_on:
      - postgres
      - redis
  
  postgres:
    image: postgres:15
    environment:
      POSTGRES_DB: myapp
      POSTGRES_USER: myapp
      POSTGRES_PASSWORD: password
    volumes:
      - postgres_data:/var/lib/postgresql/data
  
  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"
Kubernetes
# k8s/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: mithril-app
spec:
  replicas: 3
  selector:
    matchLabels:
      app: mithril-app
  template:
    metadata:
      labels:
        app: mithril-app
    spec:
      containers:
      - name: mithril-app
        image: mithril-app:latest
        ports:
        - containerPort: 3000
        env:
        - name: DB_HOST
          value: "postgres-service"

πŸ“Š Monitoring

Health Checks
// pkg/monitoring/health.go
func HealthCheck(c *fiber.Ctx) error {
    return c.JSON(fiber.Map{
        "status":    "ok",
        "timestamp": time.Now().Unix(),
        "version":   "1.0.0",
    })
}
Prometheus Metrics
// pkg/monitoring/metrics.go
func MetricsHandler(c *fiber.Ctx) error {
    // Return Prometheus metrics
    return c.Type("text/plain").Send(metrics)
}

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Submit a pull request

πŸ“„ License

MIT License - see LICENSE file for details.

πŸ™ Acknowledgments

  • Fiber - Web framework
  • GORM - ORM library
  • Laravel - PHP framework inspiration
  • Django - Python framework inspiration
  • FastAPI - Python API framework inspiration

πŸ“ž Support


Mithril Framework - Built with ❀️ in Go

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL