framework

package
v0.0.0-...-6a4645b Latest Latest
Warning

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

Go to latest
Published: May 28, 2026 License: MIT Imports: 37 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrCacheMiss = errors.New("cache miss")

ErrCacheMiss is returned when a cache key is not found.

Functions

func Bind

func Bind[T any](c *Context) (T, error)

Bind decodes JSON body into T and returns the value.

func MustMigrate

func MustMigrate(db *DB, dir string)

Types

type App

type App struct {
	*Router
}

func New

func New(options ...Option) *App

func (*App) Listen

func (a *App) Listen(addr string) error

func (*App) Run

func (a *App) Run(addrs ...string) error

Run starts the HTTP server. If addr is omitted, :8080 is used.

type Cache

type Cache interface {
	Get(ctx context.Context, key string) (string, error)
	GetBytes(ctx context.Context, key string) ([]byte, error)
	Set(ctx context.Context, key string, value any, ttl time.Duration) error
	SetBytes(ctx context.Context, key string, value []byte, ttl time.Duration) error
	Delete(ctx context.Context, keys ...string) error
	Exists(ctx context.Context, key string) (bool, error)
	RememberBytes(ctx context.Context, key string, ttl time.Duration, fn func(context.Context) ([]byte, error)) ([]byte, error)
	Close() error
}

Cache is the small ORDIN abstraction over Redis-like key/value storage.

type ConsumeOption

type ConsumeOption func(*ConsumeOptions)

ConsumeOption updates ConsumeOptions.

func WithAutoAck

func WithAutoAck() ConsumeOption

WithAutoAck enables automatic acknowledgements.

func WithConsumerName

func WithConsumerName(name string) ConsumeOption

WithConsumerName sets an AMQP consumer name.

func WithPrefetch

func WithPrefetch(count int) ConsumeOption

WithPrefetch sets channel QoS prefetch count.

func WithRequeueOnError

func WithRequeueOnError() ConsumeOption

WithRequeueOnError requeues messages when the handler returns an error.

type ConsumeOptions

type ConsumeOptions struct {
	ConsumerName   string
	Prefetch       int
	AutoAck        bool
	RequeueOnErr   bool
	DeclareDurable bool
}

ConsumeOptions configures queue consumption.

type Context

type Context struct {
	Writer  http.ResponseWriter
	Request *http.Request
	// contains filtered or unexported fields
}

func (*Context) BadRequest

func (c *Context) BadRequest(message string) error

func (*Context) BindJSON

func (c *Context) BindJSON(dst any) error

func (*Context) Cache

func (c *Context) Cache() Cache

Cache returns the configured cache service.

func (*Context) Created

func (c *Context) Created(data any) error

func (*Context) Ctx

func (c *Context) Ctx() context.Context

Ctx returns the request context.

func (*Context) Error

func (c *Context) Error(code int, message string) error

func (*Context) Forbidden

func (c *Context) Forbidden(message string) error

func (*Context) Header

func (c *Context) Header(name string) string

func (*Context) JSON

func (c *Context) JSON(code int, data any, exclude ...[]string) error

JSON sends a JSON response.

Usage:

return c.JSON(200, account)
return c.JSON(200, account, []string{"password", "token"})

Excluded fields are matched by json tag name first, then by Go struct field name.

func (*Context) MustCache

func (c *Context) MustCache() Cache

MustCache returns the configured cache service or panics.

func (*Context) MustQueue

func (c *Context) MustQueue() Queue

MustQueue returns the configured queue service or panics.

func (*Context) MustRedis

func (c *Context) MustRedis() *RedisCache

MustRedis returns the configured Redis-backed cache service or panics.

func (*Context) MustSFTP

func (c *Context) MustSFTP() FileTransport

MustSFTP returns the configured file transport service or panics.

func (*Context) MustScheduler

func (c *Context) MustScheduler() *Scheduler

MustScheduler returns the configured scheduler or panics.

func (*Context) MustStorage

func (c *Context) MustStorage() Storage

MustStorage returns the configured object storage service or panics.

func (*Context) NoContent

func (c *Context) NoContent() error

func (*Context) NotFound

func (c *Context) NotFound(message string) error

func (*Context) OK

func (c *Context) OK(data any) error

func (*Context) Param

func (c *Context) Param(name string) string

func (*Context) ParamInt

func (c *Context) ParamInt(name string) (int, error)

ParamInt reads a route parameter and converts it to int.

func (*Context) Query

func (c *Context) Query(name string) string

func (*Context) Queue

func (c *Context) Queue() Queue

Queue returns the configured queue service.

func (*Context) Redis

func (c *Context) Redis() *RedisCache

Redis returns the configured Redis-backed cache service when available.

func (*Context) SFTP

func (c *Context) SFTP() FileTransport

SFTP returns the configured file transport service.

func (*Context) Scheduler

func (c *Context) Scheduler() *Scheduler

Scheduler returns the configured in-process scheduler.

func (*Context) Status

func (c *Context) Status(code int) *Context

func (*Context) Storage

func (c *Context) Storage() Storage

Storage returns the configured object storage service.

func (*Context) Text

func (c *Context) Text(code int, text string) error

func (*Context) Unauthorized

func (c *Context) Unauthorized(message string) error

func (*Context) View

func (c *Context) View(name string, data any) error

View renders a configured HTML view with HTTP 200.

func (*Context) ViewStatus

func (c *Context) ViewStatus(code int, name string, data any) error

ViewStatus renders a configured HTML view with a custom HTTP status.

type DB

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

func ConnectPostgres

func ConnectPostgres(dsn string) (*DB, error)

func MustPostgres

func MustPostgres(dsn string) *DB

func MustPostgresEnv

func MustPostgresEnv(key, fallback string) *DB

func (*DB) Close

func (db *DB) Close() error

func (*DB) DSN

func (db *DB) DSN() string

func (*DB) Exec

func (db *DB) Exec(ctx context.Context, query string, args ...any) (sql.Result, error)

func (*DB) SQL

func (db *DB) SQL() *sql.DB

func (*DB) Table

func (db *DB) Table(name string) *QueryBuilder

type Data

type Data map[string]any

Data is a small convenience alias for view data.

type FileTransport

type FileTransport interface {
	Upload(ctx context.Context, localPath, remotePath string, options ...SFTPUploadOption) (*SFTPUploadResult, error)
	UploadReader(ctx context.Context, remotePath string, body io.Reader, options ...SFTPUploadOption) (*SFTPUploadResult, error)
	Close() error
}

FileTransport describes a remote file delivery backend.

type HandlerFunc

type HandlerFunc func(*Context) error

func JSON

func JSON(data any) HandlerFunc

JSON returns a handler that responds with 200 application/json.

func Text

func Text(text string) HandlerFunc

Text returns a handler that responds with 200 text/plain.

type Job

type Job struct {
	Queue       string
	Body        []byte
	ContentType string
	Headers     map[string]any
	Timestamp   time.Time
}

Job is a single queue delivery.

func (Job) DecodeJSON

func (j Job) DecodeJSON(dst any) error

DecodeJSON decodes a JSON job body into dst.

type JobHandler

type JobHandler func(context.Context, Job) error

JobHandler handles one queue delivery. Return an error to reject/nack it.

type Middleware

type Middleware func(HandlerFunc) HandlerFunc

func Logger

func Logger() Middleware

func Recover

func Recover() Middleware

type Migrator

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

func NewMigrator

func NewMigrator(db *DB) *Migrator

func (*Migrator) Run

func (m *Migrator) Run(ctx context.Context, dir string) error

type Option

type Option func(*App)

Option configures an App during creation.

func Dev

func Dev() Option

Dev enables a small development preset: panic recovery + request logging.

func WithCache

func WithCache(cache Cache) Option

WithCache sets the default cache service available through Context.Cache().

func WithMiddleware

func WithMiddleware(middlewares ...Middleware) Option

WithMiddleware registers global middleware during app creation.

func WithQueue

func WithQueue(queue Queue) Option

WithQueue sets the default queue service available through Context.Queue().

func WithRedis

func WithRedis(cache Cache) Option

WithRedis is an alias for WithCache for Redis-backed applications.

func WithRenderer

func WithRenderer(renderer Renderer) Option

WithRenderer sets a custom HTML view renderer.

func WithSFTP

func WithSFTP(transport FileTransport) Option

WithSFTP sets the default SFTP transport available through Context.SFTP().

func WithScheduler

func WithScheduler(scheduler *Scheduler) Option

WithScheduler sets the default scheduler available through Context.Scheduler().

func WithStorage

func WithStorage(storage Storage) Option

WithStorage sets the default storage service available through Context.Storage().

func WithViews

func WithViews(dir string, funcs ...template.FuncMap) Option

WithViews configures the default ORDIN Blade-like view engine.

type Pipeline

type Pipeline struct {
	Name string
	// contains filtered or unexported fields
}

Pipeline is a sequential task pipeline. It is useful for file delivery, ETL-like jobs and queue/scheduler workflows.

func NewPipeline

func NewPipeline(name string) *Pipeline

NewPipeline creates a named pipeline.

func (*Pipeline) Run

func (p *Pipeline) Run(ctx context.Context, data Data) (*PipelineContext, error)

Run executes the pipeline sequentially.

func (*Pipeline) Steps

func (p *Pipeline) Steps() []PipelineStep

Steps returns a snapshot of pipeline steps.

func (*Pipeline) Use

func (p *Pipeline) Use(name string, handler PipelineFunc, options ...PipelineStepOption) *Pipeline

Use appends a step and returns the same pipeline for fluent construction.

type PipelineContext

type PipelineContext struct {
	context.Context
	Pipeline string
	Data     Data
	Events   []PipelineEvent
}

PipelineContext carries context and mutable data across pipeline steps.

func (*PipelineContext) Get

func (c *PipelineContext) Get(key string) (any, bool)

Get returns a value from pipeline data.

func (*PipelineContext) Set

func (c *PipelineContext) Set(key string, value any)

Set stores a value in pipeline data.

func (*PipelineContext) String

func (c *PipelineContext) String(key string) string

String returns a string value from pipeline data.

type PipelineEvent

type PipelineEvent struct {
	Step     string
	Attempt  int
	Duration time.Duration
	Error    error
}

PipelineEvent describes one finished pipeline step.

type PipelineFunc

type PipelineFunc func(*PipelineContext) error

PipelineFunc executes one pipeline stage.

type PipelineStep

type PipelineStep struct {
	Name    string
	Handler PipelineFunc
	Options PipelineStepOptions
}

PipelineStep is one executable pipeline stage.

type PipelineStepOption

type PipelineStepOption func(*PipelineStepOptions)

PipelineStepOption updates PipelineStepOptions.

func ContinueOnStepError

func ContinueOnStepError() PipelineStepOption

ContinueOnStepError records an error and continues to the next step.

func WithStepRetries

func WithStepRetries(retries int, delay time.Duration) PipelineStepOption

WithStepRetries retries a failing step.

func WithStepTimeout

func WithStepTimeout(timeout time.Duration) PipelineStepOption

WithStepTimeout limits one pipeline step.

type PipelineStepOptions

type PipelineStepOptions struct {
	Timeout         time.Duration
	Retries         int
	RetryDelay      time.Duration
	ContinueOnError bool
}

PipelineStepOptions configures a pipeline step.

type PublishOption

type PublishOption func(*PublishOptions)

PublishOption updates PublishOptions.

func WithExchange

func WithExchange(exchange, routingKey string) PublishOption

WithExchange publishes to a custom exchange and routing key.

func WithQueueContentType

func WithQueueContentType(contentType string) PublishOption

WithQueueContentType sets the message content type.

func WithQueueDelay

func WithQueueDelay(delay time.Duration) PublishOption

WithQueueDelay sets the x-delay header for RabbitMQ delayed-message exchange setups. It requires the RabbitMQ delayed message plugin and a compatible exchange.

func WithQueueHeaders

func WithQueueHeaders(headers map[string]any) PublishOption

WithQueueHeaders adds AMQP headers.

func WithTransientMessage

func WithTransientMessage() PublishOption

WithTransientMessage disables persistent delivery for this message.

type PublishOptions

type PublishOptions struct {
	ContentType  string
	Persistent   bool
	Exchange     string
	RoutingKey   string
	Headers      map[string]any
	Delay        time.Duration
	Mandatory    bool
	Immediate    bool
	DeliveryMode uint8
}

PublishOptions configures a queue publish.

type PutOption

type PutOption func(*PutOptions)

PutOption updates PutOptions.

func WithCacheControl

func WithCacheControl(value string) PutOption

WithCacheControl sets the object Cache-Control metadata.

func WithContentType

func WithContentType(contentType string) PutOption

WithContentType sets the object content type.

func WithObjectMetadata

func WithObjectMetadata(metadata map[string]string) PutOption

WithObjectMetadata adds user metadata to the object.

type PutOptions

type PutOptions struct {
	ContentType  string
	CacheControl string
	Metadata     map[string]string
}

PutOptions configures uploaded object metadata.

type QueryBuilder

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

func (*QueryBuilder) Delete

func (q *QueryBuilder) Delete(ctx context.Context) error

func (*QueryBuilder) First

func (q *QueryBuilder) First(ctx context.Context, dst any) error

func (*QueryBuilder) Get

func (q *QueryBuilder) Get(ctx context.Context, dst any) error

func (*QueryBuilder) Insert

func (q *QueryBuilder) Insert(ctx context.Context, model any) error

func (*QueryBuilder) Limit

func (q *QueryBuilder) Limit(n int) *QueryBuilder

func (*QueryBuilder) Offset

func (q *QueryBuilder) Offset(n int) *QueryBuilder

func (*QueryBuilder) OrderBy

func (q *QueryBuilder) OrderBy(expr string) *QueryBuilder

func (*QueryBuilder) Select

func (q *QueryBuilder) Select(cols ...string) *QueryBuilder

func (*QueryBuilder) Update

func (q *QueryBuilder) Update(ctx context.Context, values map[string]any) error

func (*QueryBuilder) Where

func (q *QueryBuilder) Where(cond string, args ...any) *QueryBuilder

type Queue

type Queue interface {
	Publish(ctx context.Context, queue string, payload []byte, options ...PublishOption) error
	PublishJSON(ctx context.Context, queue string, payload any, options ...PublishOption) error
	Consume(ctx context.Context, queue string, handler JobHandler, options ...ConsumeOption) error
	Close() error
}

Queue is the small ORDIN abstraction for background jobs/messages.

type RabbitMQConfig

type RabbitMQConfig struct {
	URL string
}

RabbitMQConfig configures RabbitMQ/AMQP 0.9.1.

func RabbitMQConfigFromEnv

func RabbitMQConfigFromEnv(prefix string) RabbitMQConfig

RabbitMQConfigFromEnv reads RABBITMQ_URL by default.

type RabbitQueue

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

RabbitQueue is the RabbitMQ implementation of Queue.

func MustRabbitQueue

func MustRabbitQueue(config RabbitMQConfig) *RabbitQueue

MustRabbitQueue creates a RabbitMQ queue backend or panics.

func NewRabbitQueue

func NewRabbitQueue(config RabbitMQConfig) (*RabbitQueue, error)

NewRabbitQueue creates a RabbitMQ queue backend.

func (*RabbitQueue) Close

func (q *RabbitQueue) Close() error

Close closes the AMQP connection.

func (*RabbitQueue) Connection

func (q *RabbitQueue) Connection() *amqp.Connection

Connection exposes the underlying AMQP connection for advanced workflows.

func (*RabbitQueue) Consume

func (q *RabbitQueue) Consume(ctx context.Context, queue string, handler JobHandler, options ...ConsumeOption) error

Consume handles messages until ctx is cancelled or the broker returns an error.

func (*RabbitQueue) Publish

func (q *RabbitQueue) Publish(ctx context.Context, queue string, payload []byte, options ...PublishOption) error

Publish sends a message to a queue. By default the message is persistent and the target queue is declared durable.

func (*RabbitQueue) PublishJSON

func (q *RabbitQueue) PublishJSON(ctx context.Context, queue string, payload any, options ...PublishOption) error

PublishJSON marshals payload as JSON and publishes it.

type RedisCache

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

RedisCache is the Redis implementation of Cache.

func MustRedisCache

func MustRedisCache(config RedisConfig) *RedisCache

MustRedisCache creates a Redis cache or panics.

func NewRedisCache

func NewRedisCache(config RedisConfig) (*RedisCache, error)

NewRedisCache creates a Redis-backed cache.

func (*RedisCache) Client

func (r *RedisCache) Client() *redis.Client

Client exposes the underlying go-redis client for advanced workflows.

func (*RedisCache) Close

func (r *RedisCache) Close() error

Close closes the Redis client.

func (*RedisCache) Delete

func (r *RedisCache) Delete(ctx context.Context, keys ...string) error

Delete removes one or more keys.

func (*RedisCache) Exists

func (r *RedisCache) Exists(ctx context.Context, key string) (bool, error)

Exists checks if key exists.

func (*RedisCache) Get

func (r *RedisCache) Get(ctx context.Context, key string) (string, error)

Get reads a string value.

func (*RedisCache) GetBytes

func (r *RedisCache) GetBytes(ctx context.Context, key string) ([]byte, error)

GetBytes reads a binary value.

func (*RedisCache) Ping

func (r *RedisCache) Ping(ctx context.Context) error

Ping checks Redis availability.

func (*RedisCache) RememberBytes

func (r *RedisCache) RememberBytes(ctx context.Context, key string, ttl time.Duration, fn func(context.Context) ([]byte, error)) ([]byte, error)

RememberBytes returns cached bytes or stores the result of fn with the given TTL.

func (*RedisCache) Set

func (r *RedisCache) Set(ctx context.Context, key string, value any, ttl time.Duration) error

Set writes a value with optional TTL. Use ttl=0 for no expiration.

func (*RedisCache) SetBytes

func (r *RedisCache) SetBytes(ctx context.Context, key string, value []byte, ttl time.Duration) error

SetBytes writes a binary value with optional TTL. Use ttl=0 for no expiration.

type RedisConfig

type RedisConfig struct {
	Addr         string
	Username     string
	Password     string
	DB           int
	Prefix       string
	TLS          bool
	DialTimeout  time.Duration
	ReadTimeout  time.Duration
	WriteTimeout time.Duration
}

RedisConfig configures a Redis cache/client connection.

func RedisConfigFromEnv

func RedisConfigFromEnv(prefix string) RedisConfig

RedisConfigFromEnv reads REDIS_* variables by default.

type Renderer

type Renderer interface {
	Render(w http.ResponseWriter, status int, name string, data any) error
}

Renderer renders a named template into an HTTP response.

type Resource

type Resource struct {
	Index  HandlerFunc
	Show   HandlerFunc
	Store  HandlerFunc
	Update HandlerFunc
	Delete HandlerFunc
}

Resource describes conventional CRUD handlers.

type Router

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

func NewRouter

func NewRouter() *Router

func (*Router) Delete

func (r *Router) Delete(path string, h HandlerFunc, middlewares ...Middleware)

func (*Router) Get

func (r *Router) Get(path string, h HandlerFunc, middlewares ...Middleware)

func (*Router) Group

func (r *Router) Group(prefix string, fn func(*Router), middlewares ...Middleware)

Group keeps the callback style API for backward compatibility.

func (*Router) Handle

func (r *Router) Handle(pattern string, h HandlerFunc, middlewares ...Middleware)

Handle accepts a compact pattern such as "GET /users/{id}".

func (*Router) Patch

func (r *Router) Patch(path string, h HandlerFunc, middlewares ...Middleware)

func (*Router) Post

func (r *Router) Post(path string, h HandlerFunc, middlewares ...Middleware)

func (*Router) Put

func (r *Router) Put(path string, h HandlerFunc, middlewares ...Middleware)

func (*Router) Resource

func (r *Router) Resource(path string, resource Resource, middlewares ...Middleware)

Resource registers conventional CRUD routes for a resource path.

func (*Router) Route

func (r *Router) Route(prefix string, middlewares ...Middleware) *Router

Route returns a fluent route group. Routes added to it are registered on the same router.

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

func (*Router) Use

func (r *Router) Use(middlewares ...Middleware)

type S3Config

type S3Config struct {
	Endpoint        string
	AccessKeyID     string
	SecretAccessKey string
	SessionToken    string
	Bucket          string
	Region          string
	Secure          bool
	CreateBucket    bool
}

S3Config configures an S3-compatible storage backend.

func S3ConfigFromEnv

func S3ConfigFromEnv(prefix string) S3Config

S3ConfigFromEnv reads an S3-compatible configuration from environment.

For prefix "S3", it reads S3_ENDPOINT, S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY, S3_SESSION_TOKEN, S3_BUCKET, S3_REGION, S3_SECURE and S3_CREATE_BUCKET.

type S3Storage

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

S3Storage is the default ORDIN Storage implementation.

func MustS3Storage

func MustS3Storage(config S3Config) *S3Storage

MustS3Storage creates an S3 storage or panics with a readable message.

func NewS3Storage

func NewS3Storage(config S3Config) (*S3Storage, error)

NewS3Storage creates an S3-compatible storage backend.

func (*S3Storage) Bucket

func (s *S3Storage) Bucket() string

Bucket returns the configured bucket name.

func (*S3Storage) Client

func (s *S3Storage) Client() *minio.Client

Client exposes the underlying MinIO client for advanced S3 operations.

func (*S3Storage) Delete

func (s *S3Storage) Delete(ctx context.Context, key string) error

Delete removes an object.

func (*S3Storage) EnsureBucket

func (s *S3Storage) EnsureBucket(ctx context.Context, region string) error

EnsureBucket creates the bucket when it does not exist.

func (*S3Storage) Exists

func (s *S3Storage) Exists(ctx context.Context, key string) (bool, error)

Exists checks if an object is available.

func (*S3Storage) Get

func (s *S3Storage) Get(ctx context.Context, key string) (io.ReadCloser, error)

Get opens an object for streaming.

func (*S3Storage) GetBytes

func (s *S3Storage) GetBytes(ctx context.Context, key string) ([]byte, error)

GetBytes downloads an object into memory.

func (*S3Storage) Put

func (s *S3Storage) Put(ctx context.Context, key string, body io.Reader, size int64, options ...PutOption) error

Put uploads an object.

func (*S3Storage) PutBytes

func (s *S3Storage) PutBytes(ctx context.Context, key string, data []byte, options ...PutOption) error

PutBytes uploads a byte slice.

func (*S3Storage) URL

func (s *S3Storage) URL(ctx context.Context, key string, expiry time.Duration) (string, error)

URL returns a temporary presigned GET URL.

type SFTPClient

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

SFTPClient uploads files to remote hosts through SFTP.

func MustSFTPClient

func MustSFTPClient(config SFTPConfig) *SFTPClient

MustSFTPClient creates an SFTP client or panics.

func NewSFTPClient

func NewSFTPClient(config SFTPConfig) (*SFTPClient, error)

NewSFTPClient creates a new SFTP client.

func (*SFTPClient) Close

func (c *SFTPClient) Close() error

Close closes the SFTP and SSH clients.

func (*SFTPClient) Upload

func (c *SFTPClient) Upload(ctx context.Context, localPath, remotePath string, options ...SFTPUploadOption) (*SFTPUploadResult, error)

Upload uploads a local file and verifies SHA-256 after upload by default.

func (*SFTPClient) UploadReader

func (c *SFTPClient) UploadReader(ctx context.Context, remotePath string, body io.Reader, options ...SFTPUploadOption) (*SFTPUploadResult, error)

UploadReader uploads content from a reader and verifies SHA-256 after upload by default.

type SFTPConfig

type SFTPConfig struct {
	Host                  string
	Port                  int
	Username              string
	Password              string
	PrivateKey            string
	PrivateKeyPath        string
	PrivateKeyPassphrase  string
	KnownHostsPath        string
	InsecureIgnoreHostKey bool
	Timeout               time.Duration
}

SFTPConfig configures SSH/SFTP delivery.

func SFTPConfigFromEnv

func SFTPConfigFromEnv(prefix string) SFTPConfig

SFTPConfigFromEnv reads SFTP_* variables by default.

type SFTPUploadOption

type SFTPUploadOption func(*SFTPUploadOptions)

SFTPUploadOption updates SFTPUploadOptions.

func WithSFTPMkdirAll

func WithSFTPMkdirAll() SFTPUploadOption

WithSFTPMkdirAll creates the remote parent directory before upload.

func WithSFTPMode

func WithSFTPMode(mode os.FileMode) SFTPUploadOption

WithSFTPMode sets the remote file mode after upload.

func WithoutSFTPChecksum

func WithoutSFTPChecksum() SFTPUploadOption

WithoutSFTPChecksum disables post-upload checksum verification.

type SFTPUploadOptions

type SFTPUploadOptions struct {
	MkdirAll       bool
	VerifyChecksum bool
	Mode           os.FileMode
	// contains filtered or unexported fields
}

SFTPUploadOptions configures an SFTP upload.

type SFTPUploadResult

type SFTPUploadResult struct {
	RemotePath     string
	Size           int64
	ChecksumSHA256 string
	Verified       bool
}

SFTPUploadResult describes the completed upload and checksum verification.

type ScheduleOption

type ScheduleOption func(*ScheduleOptions)

ScheduleOption updates ScheduleOptions.

func RunImmediately

func RunImmediately() ScheduleOption

RunImmediately starts the job once as soon as the scheduler starts.

func Singleton

func Singleton() ScheduleOption

Singleton prevents overlapping executions of the same job.

func WithScheduleErrorHandler

func WithScheduleErrorHandler(handler func(string, error)) ScheduleOption

WithScheduleErrorHandler receives job errors without stopping the scheduler.

func WithScheduleTimeout

func WithScheduleTimeout(timeout time.Duration) ScheduleOption

WithScheduleTimeout limits each job execution time.

type ScheduleOptions

type ScheduleOptions struct {
	RunImmediately bool
	Singleton      bool
	Timeout        time.Duration
	OnError        func(string, error)
}

ScheduleOptions configures scheduled jobs.

type ScheduledFunc

type ScheduledFunc func(context.Context) error

ScheduledFunc is executed by the scheduler.

type ScheduledJob

type ScheduledJob struct {
	Name    string
	Trigger Trigger
	Handler ScheduledFunc
	Options ScheduleOptions
	// contains filtered or unexported fields
}

ScheduledJob is a registered scheduler task.

func (*ScheduledJob) LastError

func (j *ScheduledJob) LastError() error

LastError returns the last handler error, if any.

type Scheduler

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

Scheduler runs in-process recurring jobs. For distributed deployments, guard jobs with Redis locks or run the scheduler in one worker process only.

func NewScheduler

func NewScheduler() *Scheduler

NewScheduler creates an empty in-process scheduler.

func (*Scheduler) DailyAt

func (s *Scheduler) DailyAt(name, at string, handler ScheduledFunc, options ...ScheduleOption) (*ScheduledJob, error)

DailyAt registers a daily job. Accepted time formats: HH:MM and HH:MM:SS.

func (*Scheduler) Every

func (s *Scheduler) Every(name string, interval time.Duration, handler ScheduledFunc, options ...ScheduleOption) *ScheduledJob

Every registers a recurring job by interval.

func (*Scheduler) Jobs

func (s *Scheduler) Jobs() []*ScheduledJob

Jobs returns a snapshot of registered jobs.

func (*Scheduler) Schedule

func (s *Scheduler) Schedule(name string, trigger Trigger, handler ScheduledFunc, options ...ScheduleOption) *ScheduledJob

Schedule registers a job with a custom trigger.

func (*Scheduler) Start

func (s *Scheduler) Start(ctx context.Context) error

Start runs registered jobs until ctx is cancelled. It blocks.

func (*Scheduler) StartAsync

func (s *Scheduler) StartAsync(ctx context.Context) <-chan error

StartAsync starts the scheduler in the background and reports the final error.

type Storage

type Storage interface {
	Put(ctx context.Context, key string, body io.Reader, size int64, options ...PutOption) error
	PutBytes(ctx context.Context, key string, data []byte, options ...PutOption) error
	Get(ctx context.Context, key string) (io.ReadCloser, error)
	GetBytes(ctx context.Context, key string) ([]byte, error)
	Delete(ctx context.Context, key string) error
	Exists(ctx context.Context, key string) (bool, error)
	URL(ctx context.Context, key string, expiry time.Duration) (string, error)
}

Storage is the small ORDIN abstraction for object/file storage.

The default implementation is S3-compatible, so the same interface works with MinIO, SeaweedFS S3, AWS S3 and similar backends.

type Trigger

type Trigger interface {
	Next(after time.Time) time.Time
}

Trigger computes the next time a job should run after a given moment.

type TypedQuery

type TypedQuery[T any] struct {
	// contains filtered or unexported fields
}

TypedQuery is a small generic wrapper around QueryBuilder.

func Query

func Query[T any](db *DB, table string) *TypedQuery[T]

func Repo

func Repo[T any](db *DB, table string) *TypedQuery[T]

func (*TypedQuery[T]) All

func (q *TypedQuery[T]) All(ctx context.Context) ([]T, error)

func (*TypedQuery[T]) Builder

func (q *TypedQuery[T]) Builder() *QueryBuilder

func (*TypedQuery[T]) Create

func (q *TypedQuery[T]) Create(ctx context.Context, model T) error

func (*TypedQuery[T]) Delete

func (q *TypedQuery[T]) Delete(ctx context.Context) error

func (*TypedQuery[T]) First

func (q *TypedQuery[T]) First(ctx context.Context) (T, error)

func (*TypedQuery[T]) Limit

func (q *TypedQuery[T]) Limit(n int) *TypedQuery[T]

func (*TypedQuery[T]) Offset

func (q *TypedQuery[T]) Offset(n int) *TypedQuery[T]

func (*TypedQuery[T]) OrderBy

func (q *TypedQuery[T]) OrderBy(expr string) *TypedQuery[T]

func (*TypedQuery[T]) Select

func (q *TypedQuery[T]) Select(cols ...string) *TypedQuery[T]

func (*TypedQuery[T]) Update

func (q *TypedQuery[T]) Update(ctx context.Context, values map[string]any) error

func (*TypedQuery[T]) Where

func (q *TypedQuery[T]) Where(cond string, args ...any) *TypedQuery[T]

type ViewEngine

type ViewEngine struct {
	Dir   string
	Funcs template.FuncMap
}

ViewEngine renders native Go html/templates and Blade-like .ordin.html views.

Blade-like views are compiled to html/template before execution, so escaped output remains safe by default.

func MustViewEngine

func MustViewEngine(dir string, funcs ...template.FuncMap) *ViewEngine

MustViewEngine creates a view engine or panics with a readable message.

func NewViewEngine

func NewViewEngine(dir string, funcs ...template.FuncMap) (*ViewEngine, error)

NewViewEngine creates a renderer rooted at dir.

func (*ViewEngine) Render

func (v *ViewEngine) Render(w http.ResponseWriter, status int, name string, data any) error

Render renders a view by name, for example "welcome" or "layouts.app".

func (*ViewEngine) ViewNames

func (v *ViewEngine) ViewNames() ([]string, error)

ViewNames returns available view names. It is useful for diagnostics and tests.

Jump to

Keyboard shortcuts

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