handlers

package
v0.26.0 Latest Latest
Warning

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

Go to latest
Published: Jun 20, 2026 License: GPL-3.0 Imports: 26 Imported by: 0

README

Handlers Package Documentation

The handlers package provides reusable request-processing components for common backend workflows such as:

  • querying databases
  • executing DML operations
  • external API calls
  • pagination
  • recovery handling
  • request consumption pipelines

The package is designed around composable handler logic that can be integrated with the broader requestCore ecosystem.


Overview

The handlers package acts as an orchestration layer between:

  • request context handling
  • query execution
  • request lifecycle management
  • response generation
  • external service communication

It provides reusable building blocks to reduce repetitive endpoint and service logic.


Package Structure

handlers/
├── baseHandler.go
├── callApi.go
├── consumeHandler.go
├── dmlHandler.go
├── ormQueryHandler.go
├── pagination.go
├── persistence.go
├── queryHandler.go
├── recovery.go
└── *_test.go

Core Concepts

The handlers package follows several architectural principles:

  • reusable request-processing pipelines
  • separation of query/DML concerns
  • framework-independent business flow handling
  • composable handler utilities
  • centralized error and recovery behavior
  • testing-friendly abstractions

Handlers

Base Handler

File:

handlers/baseHandler.go

The base handler provides common functionality shared across specialized handlers.

Typical responsibilities may include:

  • request initialization
  • context preparation
  • validation flow integration
  • shared response handling
  • standardized execution behavior
  • common logging/tracing hooks

This acts as the foundation for other handler implementations.


Query Handler

File:

handlers/queryHandler.go

The query handler is responsible for read-oriented operations.

Typical use cases:

  • SELECT queries
  • fetching paginated data
  • filtering/search operations
  • response mapping
  • query execution orchestration

This handler integrates with the query layer provided by:

libQuery

and may use ORM or direct query execution depending on the implementation.


ORM Query Handler

File:

handlers/ormQueryHandler.go

The ORM query handler provides query execution behavior specifically tailored for ORM-backed flows.

Typical responsibilities:

  • ORM query execution
  • model-based retrieval
  • entity mapping
  • ORM abstraction integration
  • repository-style operations

This handler is useful when the application prefers ORM-based data access instead of raw SQL execution.


DML Handler

File:

handlers/dmlHandler.go

The DML handler manages write-oriented database operations.

Typical operations include:

  • INSERT
  • UPDATE
  • DELETE
  • transactional workflows
  • persistence orchestration

This handler centralizes mutation logic and promotes consistency across write operations.


Call API Handler

File:

handlers/callApi.go

The API call handler manages outbound HTTP/API interactions.

Typical responsibilities:

  • calling external services
  • handling authentication flows
  • request serialization
  • response parsing
  • retry/error handling integration
  • multi-service orchestration

This handler works alongside:

libCallApi

to standardize external communication behavior.


Consume Handler

File:

handlers/consumeHandler.go

The consume handler is intended for request or event consumption workflows.

Possible use cases:

  • async processing
  • event/message consumption
  • queue-driven workflows
  • background task handling
  • request replay flows

This handler helps encapsulate consumption-oriented execution patterns.


Pagination Utilities

File:

handlers/pagination.go

Pagination utilities provide reusable pagination behavior for query endpoints.

Typical capabilities:

  • page-based pagination
  • offset/limit handling
  • response metadata generation
  • pagination validation
  • standardized paging responses

Useful for:

  • REST APIs
  • admin panels
  • search endpoints
  • reporting APIs

Recovery Handler

File:

handlers/recovery.go

Recovery utilities provide panic/error recovery behavior for safer request execution.

Typical responsibilities:

  • panic recovery
  • structured error conversion
  • centralized failure handling
  • logging unexpected failures
  • preventing application crashes from request-level errors

This improves resiliency and operational stability.


Architectural Role

The handlers package sits between:

Transport Layer
    ↓
Context Initialization
    ↓
Handlers
    ↓
Query / Request / Response Layers
    ↓
Database / External Services

This creates a reusable execution pipeline that keeps endpoint logic thin and consistent.


Integration with requestCore

Handlers integrate closely with:

Package Purpose
libContext unified request context
libQuery DB/query execution
libRequest request lifecycle
response standardized responses
libCallApi external API communication
libTracing observability/tracing
libLogger structured logging

Typical Request Flow

A typical flow using handlers may look like:

Incoming Request
    ↓
Framework Adapter (Gin/Fiber/nethttp)
    ↓
libContext Initialization
    ↓
Handler Execution
    ↓
Query/DML/API Logic
    ↓
Response Generation

Observability

Handlers are designed to work with the repository’s observability stack:

  • OpenTelemetry tracing
  • structured logging
  • request-scoped metadata
  • framework-aware context propagation

This allows consistent visibility across request pipelines.


Request persistence (optional)

Handlers support optional request/result persistence via RequestPersister[Req, Resp] on generic HandlerParameters[Req, Resp].

When Persistence is nil (default for built-in query/DML/call handlers), no insert or update runs. When set, the framework calls:

  1. Insert(path, req) after parse — failure aborts the request
  2. Update(path, req) in Recovery after Finalizer and log collection — best-effort; errors are logged only and not retried
type RequestPersister[Req, Resp any] interface {
    Insert(path string, req *HandlerRequest[Req, Resp]) error
    Update(path string, req *HandlerRequest[Req, Resp]) error
}
Handler outcome fields

After the response is sent (or after a panic is captured in Recovery), Update receives a HandlerRequest with populated outcome metadata:

type HandlerOutcome struct {
    Error      error // nil on success; set on handler/init/parse/insert errors and panics
    HTTPStatus int   // HTTP status sent or intended (500 on panic); 0 if no response was sent
}

type HandlerRequest[Req, Resp any] struct {
    ...
    Outcome  HandlerOutcome
    Duration time.Duration // elapsed handler time, set in Recovery
    RespSent bool
}

HTTPStatus is recorded by the response layer (response.LastHTTPStatusLocal) after Responder().OK / Responder().Error, so it reflects the status actually emitted — not a duplicate mapping in handlers. On panic, Recovery sets HTTPStatus to 500 before Update runs.

Use trx.Outcome.Error with libError.Unwrap to build persistence outcome without reading parser locals such as errorArray.

Record ID handoff

Use a shared local key instead of per-domain names (shahkar_request_id, card_issue_id, etc.):

handlers.SetPersistedRecordID(req.W, recordID) // any type: int64, string UUID, etc.
id, ok := handlers.GetPersistedRecordID(req.W)
FuncPersister

For tests or thin adapters, implement persistence with function fields:

p := handlers.FuncPersister[MyReq, MyResp]{
    InsertFn: func(path string, req *handlers.HandlerRequest[MyReq, MyResp]) error { ... },
    UpdateFn: func(path string, req *handlers.HandlerRequest[MyReq, MyResp]) error { ... },
}

Nil function fields are no-ops. Use Persistence: nil when no persistence is needed.

Example service persister

Consumers implement RequestPersister when they need audit storage, for example delegating to libRequest:

type ServiceRequestPersister[Req, Resp any] struct{}

func (ServiceRequestPersister[Req, Resp]) Insert(path string, req *handlers.HandlerRequest[Req, Resp]) error {
    err := req.Core.RequestTools().InitRequest(req.W, req.Title, path)
    if err != nil {
        return err
    }
    handlers.SetPersistedRecordID(req.W, req.W.Parser.GetLocal("reqLog").(libRequest.RequestPtr).GetId())
    return nil
}

func (ServiceRequestPersister[Req, Resp]) Update(path string, req *handlers.HandlerRequest[Req, Resp]) error {
    reqLogLocal := req.W.Parser.GetLocal("reqLog")
    reqLog, ok := reqLogLocal.(libRequest.RequestPtr)
    if !ok || reqLog == nil {
        return nil
    }
    reqLog.Outgoing = req.Response
    if req.Outcome.Error != nil {
        if ok, errData := libError.Unwrap(req.Outcome.Error); ok {
            _ = errData // map code/status into your storage model
        }
    }
    return req.Core.RequestTools().UpdateRequestWithContext(req.W.Ctx, reqLog)
}

SQL and table shape for the service-tier request table live in application setup (libApplication/env.go), not in handlers.


Testing

The handlers package includes test coverage through files such as:

baseHanlder_test.go
persistence_test.go
callApi_test.go
consumeHandler_test.go
dmlHandler_test.go
queryHandler_test.go

This indicates handlers are designed for isolated testing and reusable execution flows.


Keep handlers orchestration-focused

Handlers should primarily:

  • coordinate flows
  • validate execution paths
  • call lower-level services
  • standardize responses

Avoid embedding heavy business logic directly in handlers.


Use specialized handlers

Prefer:

  • QueryHandler for reads
  • DMLHandler for writes
  • CallApiHandler for external communication

instead of combining unrelated concerns.


Keep business logic independent

Business logic should remain in:

  • services
  • domain modules
  • repositories

while handlers remain execution coordinators.


Suggested Future Enhancements

Potential improvements for the handlers package:

  • middleware chaining support
  • generic handler pipelines
  • transactional scopes
  • retry policies
  • circuit breaker integration
  • async workflow helpers
  • event-driven handler abstractions
  • CQRS-oriented handler separation

Summary

The handlers package provides reusable orchestration components for:

  • query execution
  • DML operations
  • external API communication
  • pagination
  • recovery
  • request consumption flows

It serves as a reusable execution layer that helps standardize backend request processing while remaining framework-independent and observability-friendly.

Documentation

Index

Constants

View Source
const (
	HeadersMap = "headersMap"
	FinalPath  = "finalPath"
)
View Source
const (
	DEFAULT_PAGE_TEXT    = "page"
	DEFAULT_SIZE_TEXT    = "size"
	DEFAULT_PAGE         = "1"
	DEFAULT_PAGE_SIZE    = "10"
	DEFAULT_MIN_PAGESIZE = 10
	DEFAULT_MAX_PAGESIZE = 100
)
View Source
const (
	Asc = "asc"
	Dsc = "desc"
)
View Source
const (
	CallApiLogEntry string = "ApiCall"
)
View Source
const PersistedRecordIDKey = "handlers.persisted_record_id"

Variables

This section is empty.

Functions

func BaseHandler

func BaseHandler[Req any, Resp any, Handler HandlerInterface[Req, Resp]](
	core requestCore.RequestCoreInterface,
	handler Handler,
	simulation bool,
	args ...any,
) any

func CallApi added in v0.9.7

func CallApi[Resp any](
	w webFramework.WebFramework,
	core requestCore.RequestCoreInterface,
	method string,
	param libCallApi.CallParam) (*Resp, error)

func CallApiForm added in v0.11.14

func CallApiForm[Req any, Resp any](
	w webFramework.WebFramework,
	core requestCore.RequestCoreInterface,
	method string,
	param *libCallApi.RemoteCallParamData[Req, Resp],
) (Resp, error)

func CallApiInternal added in v0.10.3

func CallApiInternal[Resp any](
	w webFramework.WebFramework,
	core requestCore.RequestCoreInterface,
	method string,
	param libCallApi.CallParam) (*Resp, error)

func CallApiJSON added in v0.9.52

func CallApiJSON[Req any, Resp any](
	w webFramework.WebFramework,
	core requestCore.RequestCoreInterface,
	method string,
	param *libCallApi.RemoteCallParamData[Req, Resp],
) (Resp, error)

func CallApiNoLog added in v0.9.24

func CallApiNoLog[Resp any](
	method string,
	param libCallApi.CallParam) (*Resp, error)

func CallApiWithReceipt added in v0.9.46

func CallApiWithReceipt[Resp any](
	w webFramework.WebFramework,
	core requestCore.RequestCoreInterface,
	method string,
	param libCallApi.CallParam) (*Resp, *response.Receipt, error)

func CallRemote added in v0.9.7

func CallRemote[Req any, Resp any](
	core requestCore.RequestCoreInterface,
	callArg CallArgs[Req, Resp],
	simulation bool,
	args ...string,
) any

func CallRemoteWithRespParser added in v0.9.7

func CallRemoteWithRespParser[Req any, Resp any](
	core requestCore.RequestCoreInterface,
	callArgs CallArgs[Req, Resp],
	simulation bool,
	args ...string,
) any

func ConsumeHandler added in v0.9.52

func ConsumeHandler[Req, Resp any](
	core requestCore.RequestCoreInterface,
	params *ConsumeHandlerType[Req, Resp],
	simulation bool,
) any

func Default added in v0.10.29

func Default() gin.HandlerFunc

Create a new pagination middleware with default values

func DmlHandler

func DmlHandler[Req libQuery.DmlModel](
	core requestCore.RequestCoreInterface,
	handler DmlHandlerType[Req, map[string]any],
	simulation bool,
) any

func ExecDML

func ExecDML(request libQuery.DmlModel, key, title string, w webFramework.WebFramework, core requestCore.RequestCoreInterface) (map[string]any, error)

func ExecuteDML

func ExecuteDML(request libQuery.DmlModel, key, title string, w webFramework.WebFramework, core requestCore.RequestCoreInterface) (map[string]any, error)

func ExtractHeaders added in v0.10.3

func ExtractHeaders(w webFramework.WebFramework, headers, locals []string) map[string]string

func ExtractValue added in v0.10.3

func ExtractValue(name string, source func(string) string, dest map[string]string)

func Filterate added in v0.11.2

func Filterate[Row any](paginationData libRequest.PaginationData, data []Row, filterFunc func(Filter) func(Row) bool) []Row

func FinalizeDML

func FinalizeDML(request libQuery.DmlModel, key, title string, w webFramework.WebFramework, core requestCore.RequestCoreInterface)

func GetPersistedRecordID added in v0.26.0

func GetPersistedRecordID(w webFramework.WebFramework) (any, bool)

func InitPostRequest added in v0.9.7

func InitPostRequest(
	w webFramework.WebFramework,
	reqLog libRequest.RequestPtr,
	method, url string,
	checkDuplicate func(libRequest.Request) error,
	insertRequest func(libRequest.Request) error,
	args ...any,
) (int, map[string]string, error)

func New added in v0.10.29

func New(pageText, sizeText, defaultPage, defaultPageSize string, minPageSize, maxPageSize int) gin.HandlerFunc

Create a new pagniation middleware with custom values

func Paginate added in v0.11.0

func Paginate[Row any](paginationData libRequest.PaginationData, data []Row, less func(string) func(i int, j int) bool) []Row

func PreControlDML

func PreControlDML(request libQuery.DmlModel, key, title string, w webFramework.WebFramework, core requestCore.RequestCoreInterface) error

func Query added in v0.11.6

func Query[Row, Resp any](
	core requestCore.RequestCoreInterface,
	handler QueryHandlerType[Row, Resp],
	simulation bool,
) any

func QueryHandler added in v0.9.20

func QueryHandler[Row any, Resp []Row](
	title, key, path string, queryMap map[string]libQuery.QueryCommand,
	core requestCore.RequestCoreInterface,
	mode libRequest.Type,
	validateHeader, simulation bool,
	recoveryHandler func(any),
) any

func QueryHandlerWithCaching added in v0.11.4

func QueryHandlerWithCaching[Row any, Resp []Row](
	title, key, path string, queryMap map[string]libQuery.QueryCommand,
	core requestCore.RequestCoreInterface,
	mode libRequest.Type,
	validateHeader, simulation bool,
	recoveryHandler func(any),
	caching *CachingArgs,
) any

func QueryHandlerWithOrm added in v0.16.4

func QueryHandlerWithOrm[Row any, Resp []Row](
	title, key, path string, queryMap map[string]libQuery.QueryCommand,
	core requestCore.RequestCoreInterface,
	mode libRequest.Type,
	validateHeader, simulation bool,
	recoveryHandler func(any),
	caching *CachingArgs,
) any

func QueryHandlerWithTransform added in v0.10.25

func QueryHandlerWithTransform[Row, Resp any](
	title, key, path string, queryMap map[string]libQuery.QueryCommand,
	core requestCore.RequestCoreInterface,
	mode libRequest.Type,
	validateHeader, simulation bool,
	recoveryHandler func(any),
	replacer CommandReplacer[libRequest.PaginationData],
	translator RowTranslator[Row, Resp],
	caching *CachingArgs,
) any

func QueryWithOrm added in v0.16.4

func QueryWithOrm[Row, Resp any](
	core requestCore.RequestCoreInterface,
	handler OrmHandlerType[Row, Resp],
	simulation bool,
) any

func Recovery added in v0.15.0

func Recovery[Req any, Resp any, Handler HandlerInterface[Req, Resp]](
	start time.Time,
	w webFramework.WebFramework,
	handler Handler,
	params HandlerParameters[Req, Resp],
	trx *HandlerRequest[Req, Resp],
	core requestCore.RequestCoreInterface,
	requestInserted bool,
	panicVal any,
)

func SetPersistedRecordID added in v0.26.0

func SetPersistedRecordID(w webFramework.WebFramework, id any)

Types

type CachingArgs added in v0.11.4

type CachingArgs struct {
	Cache       bool
	CacheMaxAge time.Duration
}

type CallArgs added in v0.9.7

type CallArgs[Req any, Resp any] struct {
	Title, Path, Api, Method string
	HasQuery, IsJson         bool
	HasInitializer           bool
	ForwardAuth              bool
	Transmitter              func(
		path, api, method string,
		requestByte []byte,
		headers map[string]string,
		parseRemoteResp func([]byte, string, int) (int, map[string]string, any, error),
		consumer func([]byte, string, string, string, string, map[string]string) ([]byte, string, int, error),
	) (int, map[string]string, any, error)
	Args, Locals, Headers []string
	Parser                func(respBytes []byte, desc string, status int) (int, map[string]string, any, error)
	RecoveryHandler       func(any)
}

func (CallArgs[Req, Resp]) Finalizer added in v0.9.7

func (c CallArgs[Req, Resp]) Finalizer(req HandlerRequest[Req, Resp])

func (CallArgs[Req, Resp]) Handler added in v0.9.7

func (c CallArgs[Req, Resp]) Handler(req HandlerRequest[Req, Resp]) (Resp, error)

func (CallArgs[Req, Resp]) Initializer added in v0.9.7

func (c CallArgs[Req, Resp]) Initializer(req HandlerRequest[Req, Resp]) error

func (CallArgs[Req, Resp]) Parameters added in v0.9.7

func (c CallArgs[Req, Resp]) Parameters() HandlerParameters[Req, Resp]

func (CallArgs[Req, Resp]) Simulation added in v0.9.19

func (c CallArgs[Req, Resp]) Simulation(req HandlerRequest[Req, Resp]) (Resp, error)

type CommandReplacer added in v0.10.29

type CommandReplacer[T any] struct {
	Token   string
	Builder func(T) string
}

func (CommandReplacer[T]) Replace added in v0.10.29

func (c CommandReplacer[T]) Replace(command string, data T) string

type ConsumeHandlerType added in v0.9.52

type ConsumeHandlerType[Req, Resp any] struct {
	Title           string
	Params          libCallApi.RemoteCallParamData[Req, Resp]
	Path            string
	Mode            libRequest.Type
	VerifyHeader    bool
	HasReceipt      bool
	Headers         []string
	Api             string
	Method          string
	Query           string
	RecoveryHandler func(any)
}

func (*ConsumeHandlerType[Req, Resp]) Finalizer added in v0.9.52

func (h *ConsumeHandlerType[Req, Resp]) Finalizer(req HandlerRequest[Req, Resp])

func (*ConsumeHandlerType[Req, Resp]) Handler added in v0.9.52

func (h *ConsumeHandlerType[Req, Resp]) Handler(req HandlerRequest[Req, Resp]) (Resp, error)

func (*ConsumeHandlerType[Req, Resp]) Initializer added in v0.9.52

func (h *ConsumeHandlerType[Req, Resp]) Initializer(req HandlerRequest[Req, Resp]) error

func (*ConsumeHandlerType[Req, Resp]) Parameters added in v0.9.52

func (h *ConsumeHandlerType[Req, Resp]) Parameters() HandlerParameters[Req, Resp]

func (*ConsumeHandlerType[Req, Resp]) Simulation added in v0.9.52

func (h *ConsumeHandlerType[Req, Resp]) Simulation(req HandlerRequest[Req, Resp]) (Resp, error)

type DmlHandlerType

type DmlHandlerType[Req libQuery.DmlModel, Resp map[string]any] struct {
	Title           string
	Path            string
	Mode            libRequest.Type
	VerifyHeader    bool
	Key             string
	RecoveryHandler func(any)
}

func (DmlHandlerType[Req, Resp]) Finalizer

func (h DmlHandlerType[Req, Resp]) Finalizer(req HandlerRequest[Req, Resp])

func (DmlHandlerType[Req, Resp]) Handler

func (h DmlHandlerType[Req, Resp]) Handler(req HandlerRequest[Req, Resp]) (Resp, error)

func (DmlHandlerType[Req, Resp]) Initializer

func (h DmlHandlerType[Req, Resp]) Initializer(req HandlerRequest[Req, Resp]) error

func (DmlHandlerType[Req, Resp]) Parameters

func (h DmlHandlerType[Req, Resp]) Parameters() HandlerParameters[Req, Resp]

func (DmlHandlerType[Req, Resp]) Simulation added in v0.9.19

func (h DmlHandlerType[Req, Resp]) Simulation(req HandlerRequest[Req, Resp]) (Resp, error)

type Filter added in v0.11.2

type Filter struct {
	Field    string
	Operator string
	Value    string
	Value2nd string
}

type FuncPersister added in v0.26.0

type FuncPersister[Req, Resp any] struct {
	InsertFn func(path string, req *HandlerRequest[Req, Resp]) error
	UpdateFn func(path string, req *HandlerRequest[Req, Resp]) error
}

func (FuncPersister[Req, Resp]) Insert added in v0.26.0

func (p FuncPersister[Req, Resp]) Insert(path string, req *HandlerRequest[Req, Resp]) error

func (FuncPersister[Req, Resp]) Update added in v0.26.0

func (p FuncPersister[Req, Resp]) Update(path string, req *HandlerRequest[Req, Resp]) error

type HandlerInterface

type HandlerInterface[Req any, Resp any] interface {
	// returns handler title
	//   Request Bodymode
	//   and validate header option
	//   and optional request persistence
	//   and url path of handler
	Parameters() HandlerParameters[Req, Resp]
	// runs after validating request
	Initializer(req HandlerRequest[Req, Resp]) error
	// main handler runs after initialize
	Handler(req HandlerRequest[Req, Resp]) (Resp, error)
	// runs after sending back response
	Finalizer(req HandlerRequest[Req, Resp])
	// handles simulation mode
	Simulation(req HandlerRequest[Req, Resp]) (Resp, error)
}

type HandlerOutcome added in v0.26.0

type HandlerOutcome struct {
	Error      error
	HTTPStatus int
}

type HandlerParameters added in v0.9.45

type HandlerParameters[Req, Resp any] struct {
	Title           string
	Body            libRequest.Type
	ValidateHeader  bool
	Path            string
	HasReceipt      bool
	RecoveryHandler func(any)
	FileResponse    bool
	LogArrays       []string
	LogTags         []string
	Persistence     RequestPersister[Req, Resp]
	// Tracing parameters
	EnableTracing   bool
	TracingSpanName string
}

type HandlerRequest

type HandlerRequest[Req any, Resp any] struct {
	Title    string
	Core     requestCore.RequestCoreInterface
	Header   *libRequest.RequestHeader
	Request  *Req
	Response Resp
	W        webFramework.WebFramework
	Args     []any
	RespSent bool
	Builder  func(status int, rawResp []byte, headers map[string]string) (*Resp, error)
	Outcome  HandlerOutcome
	Duration time.Duration
	// Tracing fields
	Span    trace.Span
	SpanCtx context.Context
}

func (*HandlerRequest[Req, Resp]) AddSpanAttribute added in v0.18.0

func (hr *HandlerRequest[Req, Resp]) AddSpanAttribute(key, value string)

Tracing methods for HandlerRequest

func (*HandlerRequest[Req, Resp]) AddSpanAttributes added in v0.18.0

func (hr *HandlerRequest[Req, Resp]) AddSpanAttributes(attrs map[string]string)

func (*HandlerRequest[Req, Resp]) AddSpanEvent added in v0.18.0

func (hr *HandlerRequest[Req, Resp]) AddSpanEvent(name string, attrs map[string]string)

func (HandlerRequest[Req, Resp]) GetParser added in v0.22.0

func (hr HandlerRequest[Req, Resp]) GetParser() webFramework.RequestParser

GetParser returns the RequestParser from WebFramework for tracing

func (*HandlerRequest[Req, Resp]) RecordSpanError added in v0.18.0

func (hr *HandlerRequest[Req, Resp]) RecordSpanError(err error, attrs map[string]string)

func (*HandlerRequest[Req, Resp]) SetOutcome added in v0.26.0

func (trx *HandlerRequest[Req, Resp]) SetOutcome(err error, httpStatus int)

func (*HandlerRequest[Req, Resp]) StartChildSpan added in v0.18.0

func (hr *HandlerRequest[Req, Resp]) StartChildSpan(name string, attrs map[string]string) (context.Context, trace.Span)

type OrmHandlerType added in v0.16.4

type OrmHandlerType[Row, Resp any] struct {
	Title           string
	Path            string
	Mode            libRequest.Type
	VerifyHeader    bool
	Key             string
	DbMode          libQuery.DBMode
	Command         libQuery.QueryCommand
	Translator      RowTranslator[Row, Resp]
	RecoveryHandler func(any)
	PaginateCommand func(string, libRequest.PaginationData) string
	Cache           bool
	CacheTime       time.Time
	CacheMaxAge     time.Duration
	CacheData       map[string][]Row
	OnEmpty200      bool
}

func (OrmHandlerType[Row, Resp]) CacheKey added in v0.16.4

func (q OrmHandlerType[Row, Resp]) CacheKey(args []any) string

func (OrmHandlerType[Row, Resp]) CacheResult added in v0.16.4

func (q OrmHandlerType[Row, Resp]) CacheResult(args []any, rows []Row)

func (OrmHandlerType[Row, Resp]) CheckCache added in v0.16.4

func (q OrmHandlerType[Row, Resp]) CheckCache(args []any) []Row

func (OrmHandlerType[Req, Resp]) Finalizer added in v0.16.4

func (q OrmHandlerType[Req, Resp]) Finalizer(req HandlerRequest[Req, Resp])

func (OrmHandlerType[Row, Resp]) Handler added in v0.16.4

func (q OrmHandlerType[Row, Resp]) Handler(req HandlerRequest[Row, Resp]) (Resp, error)

func (OrmHandlerType[Row, Resp]) Initializer added in v0.16.4

func (q OrmHandlerType[Row, Resp]) Initializer(req HandlerRequest[Row, Resp]) error

func (OrmHandlerType[Row, Resp]) Parameters added in v0.16.4

func (q OrmHandlerType[Row, Resp]) Parameters() HandlerParameters[Row, Resp]

func (OrmHandlerType[Req, Resp]) Simulation added in v0.16.4

func (q OrmHandlerType[Req, Resp]) Simulation(req HandlerRequest[Req, Resp]) (Resp, error)

type QueryAllTransformer added in v0.10.25

type QueryAllTransformer[Row any, Resp []Row] struct {
}

func (QueryAllTransformer[Row, Resp]) Translate added in v0.10.25

func (s QueryAllTransformer[Row, Resp]) Translate(rows []Row, req HandlerRequest[Row, Resp]) (QueryResp[Resp], error)

func (QueryAllTransformer[Row, Resp]) TranslateWithPaginate added in v0.11.0

func (s QueryAllTransformer[Row, Resp]) TranslateWithPaginate(rows []Row, req HandlerRequest[Row, Resp], pd libRequest.PaginationData) (QueryResp[Resp], error)

type QueryHandlerType added in v0.9.20

type QueryHandlerType[Row, Resp any] struct {
	Title           string
	Path            string
	Mode            libRequest.Type
	VerifyHeader    bool
	Key             string
	DbMode          libQuery.DBMode
	Command         libQuery.QueryCommand
	Translator      RowTranslator[Row, Resp]
	RecoveryHandler func(any)
	PaginateCommand func(string, libRequest.PaginationData) string
	Cache           bool
	CacheTime       time.Time
	CacheMaxAge     time.Duration
	CacheData       map[string][]Row
	OnEmpty200      bool
}

func (QueryHandlerType[Row, Resp]) CacheKey added in v0.11.3

func (q QueryHandlerType[Row, Resp]) CacheKey(args []any) string

func (QueryHandlerType[Row, Resp]) CacheResult added in v0.11.3

func (q QueryHandlerType[Row, Resp]) CacheResult(args []any, rows []Row)

func (QueryHandlerType[Row, Resp]) CheckCache added in v0.11.3

func (q QueryHandlerType[Row, Resp]) CheckCache(args []any) []Row

func (QueryHandlerType[Req, Resp]) Finalizer added in v0.9.20

func (q QueryHandlerType[Req, Resp]) Finalizer(req HandlerRequest[Req, Resp])

func (QueryHandlerType[Row, Resp]) Handler added in v0.9.20

func (q QueryHandlerType[Row, Resp]) Handler(req HandlerRequest[Row, Resp]) (Resp, error)

func (QueryHandlerType[Row, Resp]) Initializer added in v0.9.20

func (q QueryHandlerType[Row, Resp]) Initializer(req HandlerRequest[Row, Resp]) error

func (QueryHandlerType[Row, Resp]) Parameters added in v0.9.20

func (q QueryHandlerType[Row, Resp]) Parameters() HandlerParameters[Row, Resp]

func (QueryHandlerType[Req, Resp]) Simulation added in v0.9.20

func (q QueryHandlerType[Req, Resp]) Simulation(req HandlerRequest[Req, Resp]) (Resp, error)

type QueryResp added in v0.10.28

type QueryResp[Resp any] struct {
	TotalRows int
	Resp      Resp
}

type QuerySingleTransformer added in v0.10.25

type QuerySingleTransformer[Row any, Resp []Row] struct {
}

func (QuerySingleTransformer[Row, Resp]) Translate added in v0.10.25

func (s QuerySingleTransformer[Row, Resp]) Translate(rows []Row, req HandlerRequest[Row, Resp]) (QueryResp[Resp], error)

func (QuerySingleTransformer[Row, Resp]) TranslateWithPaginate added in v0.11.0

func (s QuerySingleTransformer[Row, Resp]) TranslateWithPaginate(rows []Row, req HandlerRequest[Row, Resp], pd libRequest.PaginationData) (QueryResp[Resp], error)

type RequestPersister added in v0.25.0

type RequestPersister[Req, Resp any] interface {
	Insert(path string, req *HandlerRequest[Req, Resp]) error
	Update(path string, req *HandlerRequest[Req, Resp]) error
}

RequestPersister optionally persists request lifecycle data for a handler. When HandlerParameters.Persistence is nil, insert/update are not called.

Insert must succeed before the handler runs; failure aborts the request. Update is best-effort after the response may have been sent; the framework logs errors only and does not retry.

type RowPaginator added in v0.11.0

type RowPaginator[Row any] struct {
	Less func(libRequest.PaginationData) func(i, j int) bool
}

type RowTranslator added in v0.10.25

type RowTranslator[Row, Resp any] interface {
	Translate([]Row, HandlerRequest[Row, Resp]) (QueryResp[Resp], error)
	TranslateWithPaginate([]Row, HandlerRequest[Row, Resp], libRequest.PaginationData) (QueryResp[Resp], error)
}

type WsResponse added in v0.9.7

type WsResponse[Result any] struct {
	HttpStatus   int                      `json:"-"`
	HttpHeaders  map[string]string        `json:"-"`
	Status       int                      `json:"status"`
	Description  string                   `json:"description"`
	Result       Result                   `json:"result,omitempty"`
	ErrorData    []response.ErrorResponse `json:"errors,omitempty"`
	PrintReceipt *response.Receipt        `json:"printReceipt,omitempty"`
}

func (*WsResponse[any]) SetHeaders added in v0.9.57

func (w *WsResponse[any]) SetHeaders(headers map[string]string)

func (*WsResponse[any]) SetStatus added in v0.9.57

func (w *WsResponse[any]) SetStatus(status int)

Jump to

Keyboard shortcuts

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