{"modulePath":"github.com/bitechdev/ResolveSpec","version":"v1.3.14","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package restheadspec\n\nPackage restheadspec provides the Rest Header Spec API framework.\n\nRest Header Spec (restheadspec) is a RESTful API framework that reads query options, filters, sorting, pagination, and other parameters from HTTP headers instead of request bodies or query parameters. This approach provides a clean separation between data and metadata in API requests.\n\n### Key Features {#hdr-Key_Features}\n\n  - Header-based API configuration: All query options are passed via HTTP headers\n  - Database-agnostic: Works with both GORM and Bun ORM through adapters\n  - Router-agnostic: Supports multiple HTTP routers (Mux, BunRouter, etc.)\n  - Advanced filtering: Supports complex filter operations (eq, gt, lt, like, between, etc.)\n  - Pagination and sorting: Built-in support for limit, offset, and multi-column sorting\n  - Preloading and expansion: Support for eager loading relationships\n  - Multiple response formats: Default, simple, and Syncfusion formats\n\n### HTTP Headers {#hdr-HTTP_Headers}\n\nThe following headers are supported for configuring API requests:\n\n  - X-Filters: JSON array of filter conditions\n  - X-Columns: Comma-separated list of columns to select\n  - X-Sort: JSON array of sort specifications\n  - X-Limit: Maximum number of records to return\n  - X-Offset: Number of records to skip\n  - X-Preload: Comma-separated list of relations to preload\n  - X-Expand: Comma-separated list of relations to expand (LEFT JOIN)\n  - X-Distinct: Boolean to enable DISTINCT queries\n  - X-Skip-Count: Boolean to skip total count query\n  - X-Response-Format: Response format (detail, simple, syncfusion)\n  - X-Clean-JSON: Boolean to remove null/empty fields\n  - X-Custom-SQL-Where: Custom SQL WHERE clause (AND)\n  - X-Custom-SQL-Or: Custom SQL WHERE clause (OR)\n  - X-Custom-SQL-Join: Custom SQL JOIN clauses (pipe-separated for multiple)\n\n### Usage Example {#hdr-Usage_Example}\n\n\t// Create a handler with GORM\n\thandler := restheadspec.NewHandlerWithGORM(db)\n\n\t// Register models\n\thandler.Registry.RegisterModel(\"users\", User{})\n\n\t// Setup routes with Mux\n\tmuxRouter := mux.NewRouter()\n\trestheadspec.SetupMuxRoutes(muxRouter, handler)\n\n\t// Make a request with headers\n\t// GET /public/users\n\t// X-Filters: [{\"column\":\"age\",\"operator\":\"gt\",\"value\":18}]\n\t// X-Sort: [{\"column\":\"name\",\"direction\":\"asc\"}]\n\t// X-Limit: 10\n\n## Functions\n\n```go\nfunc DecodeParam(pStr string) (string, error)\n```\nDecodeParam - Decodes parameter string and returns unencoded string\n\n```go\nfunc ExampleAuthorizationHook(ctx *HookContext) error\n```\nExampleAuthorizationHook checks if the user has permission to perform the operation\n\n```go\nfunc ExampleBunRouterWithBunDB(bunDB *bun.DB)\n```\nExampleBunRouterWithBunDB shows usage with both BunRouter and Bun DB\n\n```go\nfunc ExampleBunRouterWithGroup(bunDB *bun.DB)\n```\nExampleBunRouterWithGroup shows how to use SetupBunRouterRoutes with a bunrouter.Group\n\n```go\nfunc ExampleCacheInvalidationHook(ctx *HookContext) error\n```\nExampleCacheInvalidationHook invalidates cache after create/update/delete\n\n```go\nfunc ExampleDataTransformHook(ctx *HookContext) error\n```\nExampleDataTransformHook modifies data before create/update\n\n```go\nfunc ExampleFilterSensitiveDataHook(ctx *HookContext) error\n```\nExampleFilterSensitiveDataHook removes sensitive data from responses\n\n```go\nfunc ExampleRelatedDataHook(ctx *HookContext) error\n```\nExampleRelatedDataHook fetches related data using the handler's database\n\n```go\nfunc ExampleTxHook(ctx *HookContext) error\n```\nExampleTxHook demonstrates using the Tx field to execute additional SQL queries The Tx field provides access to the database/transaction for custom queries\n\n```go\nfunc ExampleValidationHook(ctx *HookContext) error\n```\nExampleValidationHook validates data before create/update operations\n\n```go\nfunc ExampleWithBun(bunDB *bun.DB)\n```\nExampleWithBun shows how to switch to Bun ORM\n\n```go\nfunc ExampleWithGORM(db *gorm.DB)\n```\nExampleWithGORM shows how to use RestHeadSpec with GORM\n\n```go\nfunc GetEntity(ctx context.Context) string\n```\nGetEntity retrieves entity from context\n\n```go\nfunc GetModel(ctx context.Context) interface{}\n```\nGetModel retrieves model from context\n\n```go\nfunc GetModelPtr(ctx context.Context) interface{}\n```\nGetModelPtr retrieves model pointer from context\n\n```go\nfunc GetSchema(ctx context.Context) string\n```\nGetSchema retrieves schema from context\n\n```go\nfunc GetTableName(ctx context.Context) string\n```\nGetTableName retrieves table name from context\n\n```go\nfunc NewStandardBunRouter() *router.StandardBunRouterAdapter\n```\nNewStandardBunRouter creates a router with standard BunRouter handlers\n\n```go\nfunc NewStandardMuxRouter() *router.StandardMuxAdapter\n```\nNewStandardMuxRouter creates a router with standard Mux HTTP handlers\n\n```go\nfunc RegisterSecurityHooks(handler *Handler, securityList *security.SecurityList)\n```\nRegisterSecurityHooks registers all security-related hooks with the handler\n\n```go\nfunc SetupBunRouterRoutes(r BunRouterHandler, handler *Handler, authMiddleware MiddlewareFunc)\n```\nSetupBunRouterRoutes sets up bunrouter routes for the RestHeadSpec API Accepts bunrouter.Router or bunrouter.Group authMiddleware is optional - if provided, routes will be protected with the middleware\n\n```go\nfunc SetupExampleHooks(handler *Handler)\n```\nSetupExampleHooks demonstrates how to register hooks on a handler\n\n```go\nfunc SetupMuxRoutes(muxRouter *mux.Router, handler *Handler, authMiddleware MiddlewareFunc)\n```\nSetupMuxRoutes sets up routes for the RestHeadSpec API with Mux authMiddleware is optional - if provided, routes will be protected with the middleware Example: SetupMuxRoutes(router, handler, func(h http.Handler) http.Handler { return security.NewAuthHandler(securityList, h) })\n\n```go\nfunc WithEntity(ctx context.Context, entity string) context.Context\n```\nWithEntity adds entity to context\n\n```go\nfunc WithModel(ctx context.Context, model interface{}) context.Context\n```\nWithModel adds model to context\n\n```go\nfunc WithModelPtr(ctx context.Context, modelPtr interface{}) context.Context\n```\nWithModelPtr adds model pointer to context\n\n```go\nfunc WithOptions(ctx context.Context, options ExtendedRequestOptions) context.Context\n```\nWithOptions adds request options to context\n\n```go\nfunc WithRequestData(ctx context.Context, schema, entity, tableName string, model, modelPtr interface{}, options ExtendedRequestOptions) context.Context\n```\nWithRequestData adds all request-scoped data to context at once\n\n```go\nfunc WithSchema(ctx context.Context, schema string) context.Context\n```\nWithSchema adds schema to context\n\n```go\nfunc WithTableName(ctx context.Context, tableName string) context.Context\n```\nWithTableName adds table name to context\n\n## Types\n\n```go\ntype BunRouterHandler interface {\n\tHandle(method, path string, handler bunrouter.HandlerFunc)\n}\n```\nBunRouterHandler is an interface that both bunrouter.Router and bunrouter.Group implement\n\n```go\ntype ColumnCastInfo struct {\n\tNeedsCast     bool\n\tIsNumericType bool\n}\n```\nColumnCastInfo holds information about whether a column needs casting\n\n```go\ntype CursorDirection int\n```\nCursorDirection defines pagination direction\n\n```go\nconst (\n\tCursorForward  CursorDirection = 1\n\tCursorBackward CursorDirection = -1\n)\n```\n\n```go\ntype ExpandOption struct {\n\tRelation string\n\tColumns  []string\n\tWhere    string\n\tSort     string\n}\n```\nExpandOption represents a relation expansion configuration\n\n```go\ntype ExtendedRequestOptions struct {\n\tcommon.RequestOptions\n\n\t// Field selection\n\tCleanJSON bool\n\n\t// Advanced filtering\n\tSearchColumns  []string\n\tCustomSQLWhere string\n\tCustomSQLOr    string\n\n\t// Joins\n\tExpand        []ExpandOption\n\tCustomSQLJoin []string // Custom SQL JOIN clauses\n\tJoinAliases   []string // Extracted table aliases from CustomSQLJoin for validation\n\n\t// Advanced features\n\tAdvancedSQL map[string]string // Column -\u003e SQL expression\n\tComputedQL  map[string]string // Column -\u003e CQL expression\n\tDistinct    bool\n\tSkipCount   bool\n\tSkipCache   bool\n\tPKRow       *string\n\n\t// Response format\n\tResponseFormat string // \"simple\", \"detail\", \"syncfusion\"\n\n\t// Single record normalization - convert single-element arrays to objects\n\tSingleRecordAsObject bool\n\n\t// Transaction\n\tAtomicTransaction bool\n\n\t// X-Files configuration - comprehensive query options as a single JSON object\n\tXFiles        *XFiles\n\tXFilesPresent bool // Flag to indicate if X-Files header was provided\n}\n```\nExtendedRequestOptions extends common.RequestOptions with additional features\n\n```go\nfunc GetOptions(ctx context.Context) *ExtendedRequestOptions\n```\nGetOptions retrieves request options from context\n\n```go\nfunc (opts *ExtendedRequestOptions) GetCursorFilter(\n\ttableName string,\n\tpkName string,\n\tmodelColumns []string,\n\texpandJoins map[string]string,\n) (string, error)\n```\nGetCursorFilter generates a SQL \\`EXISTS\\` subquery for cursor-based pagination. It uses the current request's sort, cursor, joins (via Expand), and CQL (via ComputedQL).\n\nParameters:\n\n  - tableName: name of the main table (e.g. \"post\")\n  - pkName: primary key column (e.g. \"id\")\n  - modelColumns: optional list of valid main-table columns (for validation). Pass nil to skip.\n  - expandJoins: optional map\\[alias]string of JOIN clauses (e.g. \"user\": \"LEFT JOIN user ON ...\")\n\nReturns SQL snippet to embed in WHERE clause.\n\n```go\ntype FallbackHandler func(w common.ResponseWriter, r common.Request, params map[string]string)\n```\nFallbackHandler is a function that handles requests when no model is found It receives the same parameters as the Handle method\n\n```go\ntype Handler struct {\n\t// contains filtered or unexported fields\n}\n```\nHandler handles API requests using database and model abstractions This handler reads filters, columns, and options from HTTP headers\n\n```go\nfunc NewHandler(db common.Database, registry common.ModelRegistry) *Handler\n```\nNewHandler creates a new API handler with database and registry abstractions\n\n```go\nfunc NewHandlerWithBun(db *bun.DB) *Handler\n```\nNewHandlerWithBun creates a new Handler with Bun adapter\n\n```go\nfunc NewHandlerWithGORM(db *gorm.DB) *Handler\n```\nNewHandlerWithGORM creates a new Handler with GORM adapter\n\n```go\nfunc (h *Handler) FetchRowNumber(ctx context.Context, db common.Database, tableName string, pkName string, pkValue string, options ExtendedRequestOptions, model any) (int64, error)\n```\nFetchRowNumber calculates the row number of a specific record based on sorting and filtering Returns the 1-based row number of the record with the given primary key value\n\n```go\nfunc (h *Handler) GetDatabase() common.Database\n```\nGetDatabase returns the underlying database connection Implements common.SpecHandler interface\n\n```go\nfunc (h *Handler) GetRelationshipInfo(modelType reflect.Type, relationName string) *common.RelationshipInfo\n```\nGetRelationshipInfo implements common.RelationshipInfoProvider interface\n\n```go\nfunc (h *Handler) Handle(w common.ResponseWriter, r common.Request, params map[string]string)\n```\nHandle processes API requests through router-agnostic interface Options are read from HTTP headers instead of request body\n\n```go\nfunc (h *Handler) HandleGet(w common.ResponseWriter, r common.Request, params map[string]string)\n```\nHandleGet processes GET requests for metadata\n\n```go\nfunc (h *Handler) HandleOpenAPI(w common.ResponseWriter, r common.Request)\n```\nHandleOpenAPI generates and returns the OpenAPI specification\n\n```go\nfunc (h *Handler) Hooks() *HookRegistry\n```\nHooks returns the hook registry for this handler Use this to register custom hooks for operations\n\n```go\nfunc (h *Handler) SetDefaultSort(schema, name string, sort ...common.SortOption)\n```\nSetDefaultSort sets the sort order applied to list (\"read\") results when a request does not specify its own sort (no x-sort header / sort query param). Pass an empty schema and name to set a global default used by any model without a more specific default.\n\n```go\nfunc (h *Handler) SetDisallowNulls(disallow bool)\n```\nSetDisallowNulls controls whether explicit null values in update payloads are ignored. By default a key present in the payload overwrites the stored value, including \"\" and null. When true, null values are skipped and the existing value is kept (\"\" still overwrites).\n\n```go\nfunc (h *Handler) SetFallbackHandler(fallback FallbackHandler)\n```\nSetFallbackHandler sets a fallback handler to be called when no model is found If not set, the handler will simply return (pass through to next route)\n\n```go\nfunc (h *Handler) SetNullAsZero(enabled bool)\n```\nSetNullAsZero controls whether an x-fieldfilter equality against 0 on a numeric column also matches NULLs: (col = 0 OR col IS NULL). Enabled by default.\n\n```go\nfunc (h *Handler) SetOpenAPIGenerator(generator func() (string, error))\n```\nSetOpenAPIGenerator sets the OpenAPI generator function This allows avoiding circular dependencies\n\n```go\nfunc (h *Handler) ValidateAndAdjustFilterForColumnType(filter *common.FilterOption, model interface{}) ColumnCastInfo\n```\nValidateAndAdjustFilterForColumnType validates and adjusts a filter based on column type Returns ColumnCastInfo indicating whether the column should be cast to text in SQL\n\n```go\ntype HookContext struct {\n\tContext   context.Context\n\tHandler   *Handler // Reference to the handler for accessing database, registry, etc.\n\tSchema    string\n\tEntity    string\n\tTableName string\n\tModel     interface{}\n\tOptions   ExtendedRequestOptions\n\n\t// Operation being dispatched (e.g. \"read\", \"create\", \"update\", \"delete\")\n\tOperation string\n\n\t// Operation-specific fields\n\tID          string\n\tData        interface{} // For create/update operations\n\tResult      interface{} // For after hooks\n\tError       error       // For after hooks\n\tQueryFilter string      // For read operations\n\n\t// Query chain - allows hooks to modify the query before execution\n\t// Can be SelectQuery, InsertQuery, UpdateQuery, or DeleteQuery\n\tQuery interface{}\n\n\t// Response writer - allows hooks to modify response\n\tWriter common.ResponseWriter\n\n\t// Request - the original HTTP request\n\tRequest common.Request\n\n\t// Allow hooks to abort the operation\n\tAbort        bool   // If set to true, the operation will be aborted\n\tAbortMessage string // Message to return if aborted\n\tAbortCode    int    // HTTP status code if aborted\n\n\t// Tx provides access to the database/transaction for executing additional SQL\n\t// This allows hooks to run custom queries in addition to the main Query chain\n\tTx common.Database\n}\n```\nHookContext contains all the data available to a hook\n\n```go\nfunc (c *HookContext) SetTx(tx common.Database)\n```\nSetTx points the context at the transaction in use (common.TxContext).\n\n```go\ntype HookFunc func(*HookContext) error\n```\nHookFunc is the signature for hook functions It receives a HookContext and can modify it or return an error If an error is returned, the operation will be aborted\n\n```go\nfunc ExampleAuditLogHook(hookType HookType) HookFunc\n```\nExampleAuditLogHook creates audit log entries for operations\n\n```go\nfunc ExampleLoggingHook(hookType HookType) HookFunc\n```\nExampleLoggingHook logs before and after operations\n\n```go\ntype HookRegistry struct {\n\t// contains filtered or unexported fields\n}\n```\nHookRegistry manages all registered hooks\n\n```go\nfunc NewHookRegistry() *HookRegistry\n```\nNewHookRegistry creates a new hook registry\n\n```go\nfunc (r *HookRegistry) Clear(hookType HookType)\n```\nClear removes all hooks for the specified type\n\n```go\nfunc (r *HookRegistry) ClearAll()\n```\nClearAll removes all registered hooks\n\n```go\nfunc (r *HookRegistry) Count(hookType HookType) int\n```\nCount returns the number of hooks registered for a specific type\n\n```go\nfunc (r *HookRegistry) Execute(hookType HookType, ctx *HookContext) error\n```\nExecute runs all hooks for the specified type in order If any hook returns an error, execution stops and the error is returned\n\n```go\nfunc (r *HookRegistry) ExecuteBeforeOp(hookType HookType, ctx *HookContext) error\n```\nExecuteBeforeOp executes the BeforeOp hook followed by the given SQL-operation hook (BeforeRead, BeforeCreate, BeforeUpdate, BeforeDelete, or BeforeScan). BeforeOp always runs first so it can observe/veto every SQL operation regardless of type.\n\n```go\nfunc (r *HookRegistry) GetAllHookTypes() []HookType\n```\nGetAllHookTypes returns all hook types that have registered hooks\n\n```go\nfunc (r *HookRegistry) HasHooks(hookType HookType) bool\n```\nHasHooks returns true if there are any hooks registered for the specified type\n\n```go\nfunc (r *HookRegistry) Register(hookType HookType, hook HookFunc)\n```\nRegister adds a new hook for the specified hook type\n\n```go\nfunc (r *HookRegistry) RegisterMultiple(hookTypes []HookType, hook HookFunc)\n```\nRegisterMultiple registers a hook for multiple hook types\n\n```go\ntype HookType string\n```\nHookType defines the type of hook to execute\n\n```go\nconst (\n\t// BeforeHandle fires after model resolution, before operation dispatch.\n\t// Use this for auth checks that need model rules and user context simultaneously.\n\tBeforeHandle HookType = \"before_handle\"\n\n\t// Read operation hooks\n\tBeforeRead HookType = \"before_read\"\n\tAfterRead  HookType = \"after_read\"\n\n\t// Create operation hooks\n\tBeforeCreate HookType = \"before_create\"\n\tAfterCreate  HookType = \"after_create\"\n\n\t// Update operation hooks\n\tBeforeUpdate HookType = \"before_update\"\n\tAfterUpdate  HookType = \"after_update\"\n\n\t// Delete operation hooks\n\tBeforeDelete HookType = \"before_delete\"\n\tAfterDelete  HookType = \"after_delete\"\n\n\t// Scan/Execute operation hooks\n\tBeforeScan HookType = \"before_scan\"\n\n\t// BeforeOp fires immediately before every SQL operation (read, create, update, delete, scan).\n\t// Unlike BeforeHandle, which fires once before operation dispatch, BeforeOp fires at each\n\t// individual SQL-operation hook point, so it runs once per statement executed.\n\tBeforeOp HookType = \"before_op\"\n\n\t// OnTxBegin fires once, first, inside every transaction the handler opens\n\t// (including the second short transaction for post-commit work). hookCtx.Tx\n\t// is the transaction; use it to stamp transaction-local state such as RLS\n\t// settings. An error or abort rolls the transaction back.\n\tOnTxBegin HookType = common.TxHookName\n)\n```\n\n```go\ntype MiddlewareFunc func(http.Handler) http.Handler\n```\nMiddlewareFunc is a function that wraps an http.Handler with additional functionality\n\n```go\ntype XFiles struct {\n\tTableName   string      `json:\"tablename\"`\n\tSchema      string      `json:\"schema\"`\n\tPrimaryKey  string      `json:\"primarykey\"`\n\tForeignKey  string      `json:\"foreignkey\"`\n\tRelatedKey  string      `json:\"relatedkey\"`\n\tSort        []string    `json:\"sort\"`\n\tPrefix      string      `json:\"prefix\"`\n\tEditable    bool        `json:\"editable\"`\n\tRecursive   bool        `json:\"recursive\"`\n\tExpand      bool        `json:\"expand\"`\n\tRownumber   bool        `json:\"rownumber\"`\n\tSkipcount   bool        `json:\"skipcount\"`\n\tOffset      json.Number `json:\"offset\"`\n\tLimit       json.Number `json:\"limit\"`\n\tColumns     []string    `json:\"columns\"`\n\tOmitColumns []string    `json:\"omit_columns\"`\n\tCQLColumns  []string    `json:\"cql_columns\"`\n\n\tSqlJoins     []string     `json:\"sql_joins\"`\n\tSqlOr        []string     `json:\"sql_or\"`\n\tSqlAnd       []string     `json:\"sql_and\"`\n\tParentTables []*XFiles    `json:\"parenttables\"`\n\tChildTables  []*XFiles    `json:\"childtables\"`\n\tModelType    reflect.Type `json:\"-\"`\n\tParentEntity *XFiles      `json:\"-\"`\n\tLevel        uint         `json:\"-\"`\n\tErrors       []error      `json:\"-\"`\n\tFilterFields []struct {\n\t\tField    string `json:\"field\"`\n\t\tValue    string `json:\"value\"`\n\t\tOperator string `json:\"operator\"`\n\t} `json:\"filter_fields\"`\n\tCursorForward  string `json:\"cursor_forward\"`\n\tCursorBackward string `json:\"cursor_backward\"`\n}\n```\n\n","path":"github.com/bitechdev/ResolveSpec/pkg/restheadspec","name":"restheadspec","synopsis":"Package restheadspec provides the Rest Header Spec API framework.","isRedistributable":true}
