tugo

package module
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Jan 21, 2026 License: MIT Imports: 18 Imported by: 0

README

TuGo

TuGo (Turbo Go) is a Go package that auto-generates REST APIs from PostgreSQL database schemas. Inspired by Directus but lighter, focusing on simplicity and flexibility.

Features

  • Auto-discovery: Automatically expose tables with configurable prefix (e.g., api_*)
  • Full CRUD: Generated endpoints for Create, Read, Update, Delete operations
  • Filtering & Sorting: Rich query parameters for filtering, sorting, and pagination
  • Relationships: Auto-discovered foreign key relationships with expansion support
  • Authentication: Built-in JWT and session-based authentication
  • Two-Factor Auth: TOTP support for enhanced security
  • File Storage: Local and MinIO storage backends
  • Validation: Automatic validation based on database constraints
  • Middleware-first: Designed for integration into existing Gin applications
  • Permission System: Policy-based access control with row-level filtering
  • Auto-migrations: Internal migration system (no external tools required)
  • Schema Watching: Auto-detect database changes via polling or PostgreSQL LISTEN/NOTIFY
  • User Seeding: Built-in mechanism to seed admin users from config or environment
  • Custom UserStore: Support for custom user tables with embed pattern

Installation

go get github.com/thienel/tugo

Quick Start

Standalone Mode
package main

import (
    "context"
    "log"

    "github.com/thienel/tugo"
)

func main() {
    engine, err := tugo.New(tugo.Config{
        DatabaseURL: "postgres://user:pass@localhost/mydb?sslmode=disable",
        Discovery: tugo.DiscoveryConfig{
            Prefix:       "api_",
            AutoDiscover: true,
        },
        // Auto-register admin routes
        Mount: tugo.MountOptions{
            IncludeAdmin: true,
        },
        // Seed default admin user
        Seed: tugo.SeedConfig{
            Enabled: true,
            AdminUser: &tugo.SeedUser{
                Username: "admin",
                Email:    "admin@example.com",
                Password: "changeme",
                Role:     "admin",
            },
        },
    })
    if err != nil {
        log.Fatal(err)
    }
    defer engine.Close()

    if err := engine.Init(context.Background()); err != nil {
        log.Fatal(err)
    }

    log.Fatal(engine.Run(":8080"))
}
Middleware Integration
package main

import (
    "context"

    "github.com/gin-gonic/gin"
    "github.com/jmoiron/sqlx"
    "github.com/thienel/tugo"
)

func main() {
    db, _ := sqlx.Connect("postgres", "postgres://...")
    router := gin.Default()

    engine, _ := tugo.New(tugo.Config{
        DB: db,
        Discovery: tugo.DiscoveryConfig{
            Prefix:       "api_",
            AutoDiscover: true,
        },
        Mount: tugo.MountOptions{
            IncludeAdmin:     true,
            AdminPath:        "/admin",
            RequireAdminAuth: true,
        },
    })
    engine.Init(context.Background())

    // Mount TuGo routes (includes admin routes if configured)
    api := router.Group("/api/v1")
    engine.Mount(api)

    router.Run(":8080")
}

Database Setup

Table Naming Convention

TuGo discovers tables using a configurable prefix. By default, tables with api_ prefix are auto-exposed:

-- This table becomes available at /api/v1/products
CREATE TABLE api_products (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    name VARCHAR(255) NOT NULL,
    price DECIMAL(10,2),
    category_id UUID,
    created_at TIMESTAMP DEFAULT NOW()
);

-- This table becomes available at /api/v1/categories
CREATE TABLE api_categories (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    name VARCHAR(255) NOT NULL
);
Migrations

TuGo automatically runs migrations during Init(). No external migration tools required.

// Migrations run automatically
engine.Init(context.Background())

To check migration status programmatically:

import "github.com/thienel/tugo/pkg/migrate"

migrator := migrate.NewMigrator(db, logger)
status, _ := migrator.Status(ctx)
for _, s := range status {
    fmt.Printf("%s: applied=%v\n", s.Name, s.Applied)
}

User Seeding

From Configuration
engine, _ := tugo.New(tugo.Config{
    Seed: tugo.SeedConfig{
        Enabled: true,
        AdminUser: &tugo.SeedUser{
            Username: "admin",
            Email:    "admin@example.com",
            Password: "secure-password",
            Role:     "admin",
        },
    },
})
From Environment Variables

Set these environment variables and TuGo will seed the admin user automatically:

export TUGO_ADMIN_USERNAME=admin
export TUGO_ADMIN_EMAIL=admin@example.com
export TUGO_ADMIN_PASSWORD=secure-password

Schema Watching

Auto-detect database schema changes:

engine, _ := tugo.New(tugo.Config{
    SchemaWatch: tugo.SchemaWatchConfig{
        Enabled:      true,
        Mode:         "poll",         // "poll" or "notify"
        PollInterval: 30 * time.Second,
    },
})

Or trigger manually:

engine.TriggerSchemaRefresh(ctx)

Permission System

TuGo includes a policy-based permission system with row-level filtering:

import "github.com/thienel/tugo/pkg/permission"

// Create permission checker
checker := permission.NewChecker(db, logger)

// Set policy: users can only read their own records
checker.SetPolicy(ctx, userRoleID, "posts", permission.ActionRead,
    map[string]any{"author_id": "$USER_ID"}, // Row-level filter
    nil, // Field permissions
    nil, // Presets
)

// Use middleware
router.Use(permission.Middleware(checker))
Filter Variables
Variable Description
$USER_ID Current user's ID
$ROLE_ID Current user's role ID
$ROLE Current user's role name
$USERNAME Current user's username
$EMAIL Current user's email

Custom UserStore

Use custom user tables with the embed pattern:

// Define custom user type embedding auth.User
type Employee struct {
    auth.User                    // Embed base User
    DepartmentID string          `db:"department_id" json:"department_id"`
    HireDate     time.Time       `db:"hire_date" json:"hire_date"`
}

// Implement auth.UserStore interface
type EmployeeStore struct {
    db *sqlx.DB
}

func (s *EmployeeStore) GetByUsername(ctx context.Context, username string) (*auth.User, error) {
    var emp Employee
    err := s.db.GetContext(ctx, &emp,
        "SELECT * FROM employees WHERE username = $1", username)
    return &emp.User, err // Return embedded User
}

func (s *EmployeeStore) Create(ctx context.Context, user *auth.User, hash string) error {
    _, err := s.db.ExecContext(ctx,
        "INSERT INTO employees (id, username, email, password_hash) VALUES ($1, $2, $3, $4)",
        user.ID, user.Username, user.Email, hash)
    return err
}

// ... implement other UserStore methods

// Use in config
engine, _ := tugo.New(tugo.Config{
    Auth: tugo.AuthConfig{
        Methods:         []string{"jwt"},
        CustomUserStore: &EmployeeStore{db: db},
    },
})

API Endpoints

Collection Endpoints
Method Endpoint Description
GET /{collection} List items with filtering, sorting, pagination
GET /{collection}/:id Get single item by ID
POST /{collection} Create new item
PATCH /{collection}/:id Update item
DELETE /{collection}/:id Delete item
Authentication Endpoints
Method Endpoint Description
POST /auth/login Authenticate and get tokens
POST /auth/refresh Refresh access token
POST /auth/logout Revoke tokens
GET /auth/me Get current user (auth required)
POST /auth/totp/setup Generate TOTP secret
POST /auth/totp/enable Enable 2FA
POST /auth/totp/disable Disable 2FA
Admin Endpoints
Method Endpoint Description
GET /admin/collections List all collections
GET /admin/collections/:name Get collection details
POST /admin/collections Create new collection
DELETE /admin/collections/:name Drop collection
POST /admin/collections/:name/fields Add field
PATCH /admin/collections/:name/fields/:field Alter field
DELETE /admin/collections/:name/fields/:field Drop field
POST /admin/sync-schema Refresh schema
File Endpoints
Method Endpoint Description
POST /files Upload file
GET /files/:path Download file
DELETE /files/:path Delete file

Query Parameters

Filtering
GET /api/v1/products?filter[name]=iPhone
GET /api/v1/products?filter[price:gte]=100
GET /api/v1/products?filter[category_id:in]=uuid1,uuid2

Operators:

Operator Description Example
eq (default) Equal filter[status]=active
ne Not equal filter[status:ne]=deleted
gt Greater than filter[price:gt]=100
gte Greater or equal filter[price:gte]=100
lt Less than filter[price:lt]=100
lte Less or equal filter[price:lte]=100
like Case-insensitive match filter[name:like]=%iphone%
in In list filter[id:in]=1,2,3
null Is null filter[deleted_at:null]=true
notnull Is not null filter[email:notnull]=true
Sorting
GET /api/v1/products?sort=name           # ASC
GET /api/v1/products?sort=-created_at    # DESC
GET /api/v1/products?sort=-price,name    # Multiple fields
Pagination
GET /api/v1/products?page=2&limit=20

Response:

{
  "success": true,
  "data": {
    "items": [...],
    "pagination": {
      "page": 2,
      "limit": 20,
      "total": 150,
      "total_pages": 8
    }
  }
}
Relationship Expansion
GET /api/v1/products?expand=category
GET /api/v1/products?expand=category,brand
Field Selection
GET /api/v1/products?fields=id,name,price
GET /api/v1/products?search=iphone

Configuration Reference

type Config struct {
    // Database connection (provide one)
    DB          *sqlx.DB  // Existing connection
    DatabaseURL string    // Connection string

    // Table discovery
    Discovery DiscoveryConfig{
        Mode         string   // "prefix", "config", "hybrid"
        Prefix       string   // Default: "api_"
        AutoDiscover bool     // Auto-expose discovered tables
        Blacklist    []string // Tables to exclude
        Config       map[string]CollectionItemConfig
    }

    // Authentication
    Auth AuthConfig{
        Methods         []string  // "jwt", "cookie", "totp"
        CustomUserStore any       // Custom auth.UserStore implementation
        JWT JWTConfig{
            Secret     string
            Expiry     int    // Seconds (default: 86400)
            RefreshExp int    // Seconds (default: 604800)
            Issuer     string
        }
        Cookie CookieConfig{
            Name     string // Default: "tugo_session"
            MaxAge   int
            Secure   bool
            HttpOnly bool
            SameSite string
        }
        TOTP TOTPConfig{
            Issuer string
            Period int    // Default: 30
            Digits int    // Default: 6
        }
    }

    // File storage
    Storage StorageConfig{
        Default   string
        Providers map[string]StorageProvider
    }

    // Route mounting
    Mount MountOptions{
        IncludeAdmin     bool   // Auto-register admin routes
        AdminPath        string // Default: "/admin"
        RequireAdminAuth bool   // Require admin role (default: true)
    }

    // User seeding
    Seed SeedConfig{
        Enabled   bool
        AdminUser *SeedUser{
            Username string
            Email    string
            Password string
            Role     string
        }
    }

    // Schema watching
    SchemaWatch SchemaWatchConfig{
        Enabled      bool
        Mode         string        // "poll" or "notify"
        PollInterval time.Duration // Default: 30s
        Channel      string        // PG channel (default: "tugo_schema_change")
    }

    // Server (standalone mode)
    Server ServerConfig{
        Port         int           // Default: 8080
        ReadTimeout  time.Duration
        WriteTimeout time.Duration
    }
}

Examples

See the examples directory:

Response Format

All responses follow a consistent format:

Success:

{
  "success": true,
  "data": { ... }
}

Error:

{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Validation failed",
    "details": {
      "errors": [
        {"field": "email", "message": "invalid email format", "code": "invalid_email"}
      ]
    }
  }
}

System Tables

TuGo uses the following system tables (created automatically):

Table Purpose
tugo_roles Role definitions
tugo_users User accounts
tugo_sessions Session tokens
tugo_permissions Role-based permissions
tugo_collections Collection metadata
tugo_fields Field definitions
tugo_relationships Relationship metadata
tugo_migrations Migration tracking
tugo_audit_log Audit trail
tugo_files File storage metadata

License

MIT License

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AuthConfig

type AuthConfig struct {
	// Methods lists enabled authentication methods: "jwt", "cookie", "totp".
	Methods []string

	// JWT configures JWT authentication.
	JWT JWTConfig

	// Cookie configures cookie-based sessions.
	Cookie CookieConfig

	// TOTP configures time-based one-time passwords.
	TOTP TOTPConfig

	// CustomUserStore allows injecting a custom UserStore implementation.
	// If provided, TuGo will use this instead of the default DBUserStore.
	// This enables apps to use custom user tables and add business logic.
	//
	// The custom store must implement the auth.UserStore interface.
	// See auth/types.go for the interface definition.
	//
	// Example with embed pattern:
	//
	//	type Employee struct {
	//	    auth.User                    // Embed the base User
	//	    DepartmentID string          `db:"department_id" json:"department_id"`
	//	    HireDate     time.Time       `db:"hire_date" json:"hire_date"`
	//	}
	//
	//	type EmployeeStore struct {
	//	    db          *sqlx.DB
	//	    emailClient *email.Client
	//	}
	//
	//	func (s *EmployeeStore) Create(ctx context.Context, user *auth.User, hash string) error {
	//	    // Custom business logic: can access embedded User fields
	//	    _, err := s.db.ExecContext(ctx, "INSERT INTO employees ...", user.ID, user.Username, hash)
	//	    if err != nil { return err }
	//	    s.emailClient.SendWelcome(user.Email)
	//	    return nil
	//	}
	//
	//	func (s *EmployeeStore) GetByUsername(ctx context.Context, username string) (*auth.User, error) {
	//	    var emp Employee // Employee embeds auth.User
	//	    if err := s.db.GetContext(ctx, &emp, "SELECT * FROM employees WHERE username = $1", username); err != nil {
	//	        return nil, err
	//	    }
	//	    return &emp.User, nil // Return embedded User
	//	}
	//
	// Pass to TuGo config:
	//
	//	tugo.New(tugo.Config{
	//	    Auth: tugo.AuthConfig{
	//	        CustomUserStore: &EmployeeStore{db: db, emailClient: emailClient},
	//	    },
	//	})
	//
	CustomUserStore any // Must implement auth.UserStore interface
}

AuthConfig configures authentication.

type CollectionConfigMap

type CollectionConfigMap map[string]CollectionItemConfig

CollectionConfigMap maps collection names to their configuration.

type CollectionItemConfig

type CollectionItemConfig struct {
	// Enabled determines if this collection is exposed via API.
	Enabled bool

	// PublicFields limits which fields are visible.
	// nil means all fields are visible.
	PublicFields []string
}

CollectionItemConfig holds configuration for a single collection.

type Config

type Config struct {
	// DB is an existing sqlx database connection.
	// Either DB or DatabaseURL must be provided.
	DB *sqlx.DB

	// DatabaseURL is a PostgreSQL connection string.
	// Used when DB is nil to create a new connection.
	DatabaseURL string

	// Discovery configures how tables are discovered and exposed.
	Discovery DiscoveryConfig

	// Auth configures authentication methods.
	Auth AuthConfig

	// Storage configures file storage providers.
	Storage StorageConfig

	// Server configures the HTTP server (standalone mode only).
	Server ServerConfig

	// Mount configures route mounting behavior.
	Mount MountOptions

	// Seed configures user seeding on first run.
	Seed SeedConfig

	// SchemaWatch configures automatic schema change detection.
	SchemaWatch SchemaWatchConfig
}

Config holds the complete configuration for TuGo engine.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a configuration with sensible defaults.

type CookieConfig

type CookieConfig struct {
	// Name is the cookie name.
	// Default: "tugo_session"
	Name string

	// MaxAge is the cookie max age in seconds.
	MaxAge int

	// Secure sets the Secure flag.
	Secure bool

	// HttpOnly sets the HttpOnly flag.
	HttpOnly bool

	// SameSite sets the SameSite attribute.
	SameSite string
}

CookieConfig configures cookie-based sessions.

type DiscoveryConfig

type DiscoveryConfig struct {
	// Mode determines discovery strategy: "prefix", "config", or "hybrid".
	// Default: "prefix"
	Mode string

	// Prefix is the table name prefix for auto-discovery.
	// Default: "api_"
	Prefix string

	// AutoDiscover enables automatic exposure of discovered tables.
	// Default: false (requires explicit enable)
	AutoDiscover bool

	// Blacklist contains table names to always exclude.
	Blacklist []string

	// Config provides per-collection configuration overrides.
	Config CollectionConfigMap
}

DiscoveryConfig configures table discovery behavior.

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine is the main TuGo engine.

func New

func New(config Config) (*Engine, error)

New creates a new TuGo engine with the given configuration.

func (*Engine) AdminHandler

func (e *Engine) AdminHandler() *admin.Handler

AdminHandler returns the admin handler.

func (*Engine) AuthMiddleware

func (e *Engine) AuthMiddleware() gin.HandlerFunc

AuthMiddleware returns the auth middleware.

func (*Engine) AuthProvider

func (e *Engine) AuthProvider() auth.Provider

AuthProvider returns the auth provider.

func (*Engine) Close

func (e *Engine) Close() error

Close cleans up resources.

func (*Engine) DB

func (e *Engine) DB() *sqlx.DB

DB returns the database connection.

func (*Engine) GetCollections

func (e *Engine) GetCollections() []*schema.Collection

GetCollections returns all discovered collections.

func (*Engine) HasCollection

func (e *Engine) HasCollection(name string) bool

HasCollection checks if a collection exists.

func (*Engine) Init

func (e *Engine) Init(ctx context.Context) error

Init initializes the engine by discovering the schema.

func (*Engine) Mount

func (e *Engine) Mount(rg *gin.RouterGroup)

Mount mounts the TuGo API routes to a Gin router group. This is the primary use case for middleware integration. If config.Mount.IncludeAdmin is true, admin routes are automatically registered.

func (*Engine) MountAdmin

func (e *Engine) MountAdmin(rg *gin.RouterGroup)

MountAdmin mounts admin API routes (should be protected).

func (*Engine) MountWithAuth

func (e *Engine) MountWithAuth(rg *gin.RouterGroup)

MountWithAuth mounts routes with authentication middleware.

func (*Engine) MountWithOptions added in v0.2.0

func (e *Engine) MountWithOptions(rg *gin.RouterGroup, opts MountOptions)

MountWithOptions mounts the TuGo API routes with custom options.

func (*Engine) RefreshSchema

func (e *Engine) RefreshSchema(ctx context.Context) error

RefreshSchema re-discovers the database schema.

func (*Engine) Router

func (e *Engine) Router() *gin.Engine

Router returns the internal Gin router for standalone mode.

func (*Engine) Run

func (e *Engine) Run(addr string) error

Run starts the HTTP server in standalone mode.

func (*Engine) SchemaManager

func (e *Engine) SchemaManager() *schema.Manager

SchemaManager returns the schema manager.

func (*Engine) SeedFromEnv added in v0.2.0

func (e *Engine) SeedFromEnv(ctx context.Context) error

SeedFromEnv seeds users from environment variables. Looks for: TUGO_ADMIN_USERNAME, TUGO_ADMIN_EMAIL, TUGO_ADMIN_PASSWORD

func (*Engine) SeedUsers added in v0.2.0

func (e *Engine) SeedUsers(ctx context.Context) error

SeedUsers seeds default users if configured and they don't exist. This is typically called during Init or manually after setup.

func (*Engine) StartSchemaWatcher added in v0.2.0

func (e *Engine) StartSchemaWatcher(ctx context.Context) error

StartSchemaWatcher starts the schema watcher if configured.

func (*Engine) StopSchemaWatcher added in v0.2.0

func (e *Engine) StopSchemaWatcher()

StopSchemaWatcher stops the schema watcher.

func (*Engine) StorageManager

func (e *Engine) StorageManager() *storage.Manager

StorageManager returns the storage manager.

func (*Engine) TOTPManager

func (e *Engine) TOTPManager() *auth.TOTPManager

TOTPManager returns the TOTP manager.

func (*Engine) TriggerSchemaRefresh added in v0.2.0

func (e *Engine) TriggerSchemaRefresh(ctx context.Context) error

TriggerSchemaRefresh manually triggers a schema refresh.

func (*Engine) UserStore

func (e *Engine) UserStore() auth.UserStore

UserStore returns the user store.

func (*Engine) ValidatorRegistry

func (e *Engine) ValidatorRegistry() *validation.ValidatorRegistry

ValidatorRegistry returns the validator registry.

type JWTConfig

type JWTConfig struct {
	// Secret is the signing key for HS256.
	Secret string

	// Expiry is the token expiry time in seconds.
	// Default: 86400 (24 hours)
	Expiry int

	// RefreshExp is the refresh token expiry in seconds.
	// Default: 604800 (7 days)
	RefreshExp int

	// Issuer is the JWT issuer claim.
	Issuer string
}

JWTConfig configures JWT authentication.

type MountOptions added in v0.2.0

type MountOptions struct {
	// IncludeAdmin enables auto-registration of admin routes under /admin.
	// Default: false
	IncludeAdmin bool

	// AdminPath is the path prefix for admin routes.
	// Default: "/admin"
	AdminPath string

	// RequireAdminAuth requires admin role for admin routes.
	// Default: true
	RequireAdminAuth bool
}

MountOptions configures how TuGo mounts its routes.

func DefaultMountOptions added in v0.2.0

func DefaultMountOptions() MountOptions

DefaultMountOptions returns default mount options.

type PGListener added in v0.2.0

type PGListener struct {
	// contains filtered or unexported fields
}

PGListener wraps PostgreSQL LISTEN/NOTIFY functionality.

func NewPGListener added in v0.2.0

func NewPGListener(db *sqlx.DB, channel string) (*PGListener, error)

NewPGListener creates a new PostgreSQL listener.

func (*PGListener) Close added in v0.2.0

func (l *PGListener) Close()

Close closes the listener.

func (*PGListener) Notify added in v0.2.0

func (l *PGListener) Notify() <-chan struct{}

Notify returns the notification channel.

type SchemaWatchConfig added in v0.2.0

type SchemaWatchConfig struct {
	// Enabled enables schema watching.
	Enabled bool

	// Mode is the watch mode: "poll" or "notify".
	// "poll" uses periodic polling.
	// "notify" uses PostgreSQL LISTEN/NOTIFY (more efficient).
	// Default: "poll"
	Mode string

	// PollInterval is the interval between polls (for poll mode).
	// Default: 30s
	PollInterval time.Duration

	// Channel is the PostgreSQL notification channel (for notify mode).
	// Default: "tugo_schema_change"
	Channel string
}

SchemaWatchConfig configures automatic schema change detection.

func DefaultSchemaWatchConfig added in v0.2.0

func DefaultSchemaWatchConfig() SchemaWatchConfig

DefaultSchemaWatchConfig returns default schema watch configuration.

type SchemaWatcher added in v0.2.0

type SchemaWatcher struct {
	// contains filtered or unexported fields
}

SchemaWatcher watches for schema changes and triggers refresh.

func NewSchemaWatcher added in v0.2.0

func NewSchemaWatcher(engine *Engine, config SchemaWatchConfig) *SchemaWatcher

NewSchemaWatcher creates a new schema watcher.

func (*SchemaWatcher) Start added in v0.2.0

func (w *SchemaWatcher) Start(ctx context.Context) error

Start begins watching for schema changes.

func (*SchemaWatcher) Stop added in v0.2.0

func (w *SchemaWatcher) Stop()

Stop stops the schema watcher.

type SeedConfig added in v0.2.0

type SeedConfig struct {
	// Enabled enables user seeding.
	Enabled bool

	// AdminUser is the default admin user configuration.
	AdminUser *SeedUser
}

SeedConfig configures user seeding on first run.

type SeedUser added in v0.2.0

type SeedUser struct {
	Username string
	Email    string
	Password string
	Role     string // "admin", "user", etc.
}

SeedUser represents a user to seed.

type ServerConfig

type ServerConfig struct {
	// Port is the server port.
	// Default: 8080
	Port int

	// ReadTimeout is the request read timeout.
	ReadTimeout time.Duration

	// WriteTimeout is the response write timeout.
	WriteTimeout time.Duration
}

ServerConfig configures the HTTP server for standalone mode.

type StorageConfig

type StorageConfig struct {
	// Default is the default storage provider name.
	Default string

	// Providers maps names to storage provider implementations.
	Providers map[string]StorageProvider
}

StorageConfig configures file storage.

type StorageProvider

type StorageProvider interface {
	// Upload stores a file and returns the storage path.
	Upload(ctx any, file any, filename string, opts *UploadOptions) (string, error)

	// Download retrieves a file by its storage path.
	Download(ctx any, path string) (any, error)

	// Delete removes a file by its storage path.
	Delete(ctx any, path string) error

	// GetURL returns a public URL for the file.
	GetURL(path string) string
}

StorageProvider is the interface for file storage backends.

type TOTPConfig

type TOTPConfig struct {
	// Issuer is displayed in authenticator apps.
	Issuer string

	// Period is the TOTP period in seconds.
	// Default: 30
	Period int

	// Digits is the number of digits in the code.
	// Default: 6
	Digits int
}

TOTPConfig configures TOTP authentication.

type UploadOptions

type UploadOptions struct {
	// ContentType is the MIME type.
	ContentType string

	// MaxSize is the maximum file size in bytes.
	MaxSize int64
}

UploadOptions provides options for file uploads.

Directories

Path Synopsis
examples
middleware command
Package main demonstrates TuGo integration as middleware in an existing Gin application.
Package main demonstrates TuGo integration as middleware in an existing Gin application.
standalone command
Package main demonstrates TuGo in standalone server mode.
Package main demonstrates TuGo in standalone server mode.
with-auth command
Package main demonstrates TuGo with full authentication including JWT and TOTP.
Package main demonstrates TuGo with full authentication including JWT and TOTP.
pkg

Jump to

Keyboard shortcuts

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