response

package
v0.28.1 Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package response provides HTTP response and error handling for requestCore.

Safe error response (for consuming repos):

  • Do not put string(rawResp) or full upstream response bodies in libError descriptions; use size/status/hash and log details separately (see libCallApi).
  • Do not use %+v on whole response structs in error messages that can become client-visible.
  • Use only codes from a fixed catalog and ensure they are seeded/localized (e.g. SystemFault, API_*); avoid dynamic values as public error codes.

Index

Constants

View Source
const (
	// NoDataFound is the error code for missing data.
	NoDataFound = "NO-DATA-FOUND"
	// SystemFault is the error code for internal system faults.
	SystemFault = "SYSTEM_FAULT"
	// SystemFaultDesc is the default localized description for system faults.
	SystemFaultDesc = "خطای سیستمی"
)
View Source
const LastHTTPStatusLocal = "response.http_status"

LastHTTPStatusLocal is the local-storage key for the most recent HTTP status code.

View Source
const MaxDescriptionLength = 512

MaxDescriptionLength is the maximum length of error description sent to API clients.

Variables

This section is empty.

Functions

func GetDescFromCode added in v0.3.21

func GetDescFromCode(code string, _ any, errDescList map[string]string) (string, string)

GetDescFromCode returns (code, description) for API response. When code is not in errDescList, it returns a safe fallback (SystemFault + localized text) and never exposes raw data.

func GetStack added in v0.9.40

func GetStack(skip int, exclude string) string

GetStack returns a formatted caller stack frame, skipping framework-internal files.

func JustPrintResp

func JustPrintResp(respBytes []byte, _ string, status int) (int, map[string]string, any, error)

JustPrintResp unmarshals and logs a remote response without returning parsed data.

func LastHTTPStatus added in v0.26.0

func LastHTTPStatus(w webFramework.WebFramework) int

LastHTTPStatus returns the HTTP status code recorded by the most recent respond call.

func ParseRemoteRespJSON added in v0.28.1

func ParseRemoteRespJSON(respBytes []byte, _ string, status int) (int, map[string]string, any, error)

ParseRemoteRespJSON parses a remote JSON response and extracts status, error details, and result.

func ParseWsRemoteResp

func ParseWsRemoteResp(respBytes []byte, _ string, status int) (int, map[string]string, any, error)

ParseWsRemoteResp parses a remote JSON response and returns the full WsRemoteResponse on success.

func SanitizeForClient added in v0.22.6

func SanitizeForClient(candidate any, maxLen int) string

SanitizeForClient turns a candidate description into a safe string for API output. - If candidate is a string: trims, applies max length, and optionally redacts sensitive patterns. - If candidate is not a string (map, struct, etc.): returns SystemFaultDesc without dumping the value.

Types

type DbResponse

type DbResponse struct {
	Status      int    `json:"status"`
	Description string `json:"description"`
	Result      any    `json:"result"`
	ErrorCode   string `json:"error_code,omitempty"`
}

DbResponse represents the standard structure of a database query response.

type ErrorData added in v0.9.5

type ErrorData struct {
	Status      int
	Description string
	Message     any
	// contains filtered or unexported fields
}

ErrorData holds structured error information including status, description, message, and child errors.

func (ErrorData) Child added in v0.9.5

func (e ErrorData) Child(err ErrorState) ErrorState

Child appends an ErrorState as a child to this error and returns the updated state.

func (ErrorData) ChildErr added in v0.9.5

func (e ErrorData) ChildErr(err error) ErrorState

ChildErr wraps a standard error as a child ErrorState and appends it to the chain.

func (ErrorData) Error added in v0.9.5

func (e ErrorData) Error() string

Error returns a formatted multi-line string representation of the error chain.

func (ErrorData) Format added in v0.9.13

func (e ErrorData) Format(header string, stack *strings.Builder)

Format writes a structured text representation of the error and its children into the given builder.

func (ErrorData) GetDescription added in v0.9.5

func (e ErrorData) GetDescription() string

GetDescription returns the error description string.

func (ErrorData) GetInput added in v0.9.6

func (e ErrorData) GetInput() any

GetInput returns the input data associated with the error.

func (ErrorData) GetMessage added in v0.9.5

func (e ErrorData) GetMessage() any

GetMessage returns the error message payload.

func (ErrorData) GetStatus added in v0.9.5

func (e ErrorData) GetStatus() int

GetStatus returns the HTTP status code associated with the error.

func (*ErrorData) Input added in v0.9.5

func (e *ErrorData) Input(in any) ErrorState

Input associates input data with the error and returns the updated ErrorState.

func (ErrorData) LogValue added in v0.15.0

func (e ErrorData) LogValue() slog.Value

LogValue implements slog.LogValuer and returns a grouped value with fields redacted. See https://pkg.go.dev/log/slog#LogValuer

func (ErrorData) SetDescription added in v0.9.5

func (e ErrorData) SetDescription(desc string) ErrorState

SetDescription sets the error description and returns the updated ErrorState.

func (ErrorData) SetMessage added in v0.9.5

func (e ErrorData) SetMessage(msg any) ErrorState

SetMessage sets the error message payload and returns the updated ErrorState.

func (ErrorData) SetStatus added in v0.9.5

func (e ErrorData) SetStatus(status int) ErrorState

SetStatus sets the HTTP status code and returns the updated ErrorState.

func (ErrorData) WsResponse added in v0.9.5

func (e ErrorData) WsResponse() string

WsResponse returns a hash-like string combining the error's description, source, input, message, and status.

type ErrorResponse

type ErrorResponse struct {
	Code        string `json:"code"`
	Description string `json:"description"`
}

ErrorResponse represents a single error entry returned to API clients.

func FormatErrorResp

func FormatErrorResp(errs error, trans ut.Translator) []ErrorResponse

FormatErrorResp translates validator validation errors into a slice of ErrorResponse using the given translator.

func GetErrorsArray

func GetErrorsArray(message string, data any) []ErrorResponse

GetErrorsArray builds a slice of ErrorResponse from a message and data, handling pre-built error arrays.

func GetErrorsArrayWithMap

func GetErrorsArrayWithMap(incomingDesc string, data any, errDescList map[string]string) []ErrorResponse

GetErrorsArrayWithMap resolves error codes against a description map to produce localized ErrorResponse entries.

type ErrorState

type ErrorState interface {
	Error() string
	Input(in any) ErrorState
	GetInput() any
	WsResponse() string
	SetStatus(int) ErrorState
	SetDescription(string) ErrorState
	SetMessage(any) ErrorState
	ChildErr(error) ErrorState
	Child(ErrorState) ErrorState
	GetStatus() int
	GetDescription() string
	GetMessage() any
	LogValue() slog.Value
}

ErrorState defines the interface for structured error data with chaining and logging support.

func Error

func Error(status int, desc string, message any, err error) ErrorState

Error creates an ErrorState with the given status, description, message, and wrapped error.

func Errors added in v0.9.12

func Errors(status int, desc string, message any, err ErrorState) ErrorState

Errors creates an ErrorState by chaining an existing ErrorState with a new status and description.

func ToError

func ToError(desc string, message any, err error) ErrorState

ToError creates an ErrorState with an internal-server-error status from the given description, message, and error.

func ToErrorState

func ToErrorState(err error) ErrorState

ToErrorState converts a standard error into an ErrorState with source tracking.

func Unwrap added in v0.15.0

func Unwrap(err error) (bool, ErrorState)

Unwrap attempts to extract an ErrorState from the given error, returning whether it succeeded.

type FileResponse added in v0.10.4

type FileResponse struct {
	FileName string `json:"fileName"`
	Path     string `json:"path"`
}

FileResponse holds the file name and path for a file-download response.

type Receipt

type Receipt struct {
	ID    string `json:"id"`
	Title string `json:"title"`
	Rows  []any  `json:"rows"`
}

Receipt represents a printable receipt with an ID, title, and data rows.

type RespData added in v0.10.4

type RespData struct {
	Code           int              `json:"code"`
	Status         int              `json:"status"`
	Message        string           `json:"message"`
	Type           RespType         `json:"type"`
	JSON           any              `json:"description"`
	PrintData      *Receipt         `json:"receipt"`
	Attachment     *FileResponse    `json:"attachment"`
	PreBuiltErrors *[]ErrorResponse `json:"-"` // when set, used instead of GetErrorsArray (e.g. for PublicDescription)
}

RespData holds all fields needed to construct an HTTP response.

type RespType added in v0.10.4

type RespType int

RespType identifies the kind of response payload to send.

const (
	// JSON indicates a plain JSON response.
	JSON RespType = iota
	// JSONWithReceipt indicates a JSON response that includes a printable receipt.
	JSONWithReceipt
	// FileAttachment indicates a file-download response.
	FileAttachment
)

type ResponseHandler

type ResponseHandler interface {
	OK(w webFramework.WebFramework, resp any)
	OKWithReceipt(w webFramework.WebFramework, resp any, receipt *Receipt)
	OKWithAttachment(w webFramework.WebFramework, file *FileResponse)
	Error(w webFramework.WebFramework, err error)
}

ResponseHandler defines the interface for sending success and error HTTP responses.

type WebHanlder added in v0.15.0

type WebHanlder struct {
	MessageDesc map[string]string
	ErrorDesc   map[string]string
}

WebHanlder holds description lookup maps for building API error responses.

func (WebHanlder) Error added in v0.15.0

func (m WebHanlder) Error(w webFramework.WebFramework, err error)

Error handles an error by logging it and sending an appropriate error response to the client.

func (WebHanlder) GetErrorsArray added in v0.15.0

func (m WebHanlder) GetErrorsArray(message string, data any) []ErrorResponse

GetErrorsArray builds a slice of ErrorResponse from a message and data using the handler's error description map.

func (WebHanlder) OK added in v0.15.0

func (m WebHanlder) OK(w webFramework.WebFramework, resp any)

OK sends a successful JSON response with HTTP 200 and the given data.

func (WebHanlder) OKWithAttachment added in v0.15.0

func (m WebHanlder) OKWithAttachment(w webFramework.WebFramework, attachment *FileResponse)

OKWithAttachment sends a successful file-attachment response with HTTP 200.

func (WebHanlder) OKWithReceipt added in v0.15.0

func (m WebHanlder) OKWithReceipt(w webFramework.WebFramework, resp any, receipt *Receipt)

OKWithReceipt sends a successful JSON response with an optional printable receipt.

func (WebHanlder) Respond added in v0.15.0

func (m WebHanlder) Respond(code, status int, message string, data any, abort bool, w webFramework.WebFramework)

Respond sends a JSON response with the given code, status, message, and data, optionally aborting the request chain.

func (WebHanlder) RespondWithAttachment added in v0.15.0

func (m WebHanlder) RespondWithAttachment(code, status int, message string, file *FileResponse, abort bool, w webFramework.WebFramework)

RespondWithAttachment sends a file-attachment response with the given code, status, and message.

func (WebHanlder) RespondWithReceipt added in v0.15.0

func (m WebHanlder) RespondWithReceipt(code, status int, message string, data any, printData *Receipt, abort bool, w webFramework.WebFramework)

RespondWithReceipt sends a JSON response with an optional printable receipt and abort control.

type WsRemoteResponse

type WsRemoteResponse struct {
	Status      int             `json:"status"`
	Description string          `json:"description"`
	Result      any             `json:"result,omitempty"`
	ErrorData   []ErrorResponse `json:"errors,omitempty"`
}

WsRemoteResponse represents the standard structure of a remote API response.

func (WsRemoteResponse) ToErrorState added in v0.1.7

func (e WsRemoteResponse) ToErrorState() ErrorState

ToErrorState converts a WsRemoteResponse into an ErrorState for error chaining.

type WsResponse

type WsResponse struct {
	Status       int      `json:"status"`
	Description  string   `json:"description"`
	Result       any      `json:"result,omitempty"`
	ErrorData    any      `json:"errors,omitempty"`
	PrintReceipt *Receipt `json:"printReceipt,omitempty"`
}

WsResponse represents the HTTP response sent to the client.

func (WsResponse) LogValue added in v0.22.5

func (r WsResponse) LogValue() slog.Value

LogValue returns a structured slog.Value for logging the WsResponse, redacting error details on failure.

Jump to

Keyboard shortcuts

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