server

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Sep 13, 2025 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Package server provides enhanced HTTP handler functionality with type-safe request/response handling.

Package server provides HTTP server functionality using Echo framework. It includes middleware setup, routing, and request handling.

Package server provides request validation functionality. It wraps go-playground/validator with custom validation logic and error formatting.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CORS

func CORS() echo.MiddlewareFunc

CORS returns a CORS middleware configured for the application. It allows cross-origin requests with appropriate security headers.

func DELETE added in v0.3.0

func DELETE[T any, R any](hr *HandlerRegistry, e *echo.Echo, path string, handler HandlerFunc[T, R])

DELETE registers a DELETE handler.

func GET added in v0.3.0

func GET[T any, R any](hr *HandlerRegistry, e *echo.Echo, path string, handler HandlerFunc[T, R])

GET registers a GET handler.

func Logger

func Logger(log logger.Logger) echo.MiddlewareFunc

Logger returns a request logging middleware using structured logging. It logs HTTP requests with method, URI, status, latency, and request ID.

func PATCH added in v0.3.0

func PATCH[T any, R any](hr *HandlerRegistry, e *echo.Echo, path string, handler HandlerFunc[T, R])

PATCH registers a PATCH handler.

func POST added in v0.3.0

func POST[T any, R any](hr *HandlerRegistry, e *echo.Echo, path string, handler HandlerFunc[T, R])

POST registers a POST handler.

func PUT added in v0.3.0

func PUT[T any, R any](hr *HandlerRegistry, e *echo.Echo, path string, handler HandlerFunc[T, R])

PUT registers a PUT handler.

func PerformanceStats

func PerformanceStats() echo.MiddlewareFunc

PerformanceStats returns middleware that initializes operation tracking for each request. It adds both AMQP message counter and database operation counter to the request context that can be incremented by messaging clients and database layer, then logged in the request logger.

func RateLimit

func RateLimit(requestsPerSecond int) echo.MiddlewareFunc

RateLimit returns a rate limiting middleware with the specified requests per second. It limits the number of requests from each IP address to prevent abuse.

func RegisterHandler added in v0.3.0

func RegisterHandler[T any, R any](
	hr *HandlerRegistry,
	e *echo.Echo,
	method, path string,
	handler HandlerFunc[T, R],
)

Register registers a typed handler with the Echo instance.

func SetupMiddlewares

func SetupMiddlewares(e *echo.Echo, log logger.Logger, cfg *config.Config)

SetupMiddlewares configures and registers all HTTP middlewares for the Echo server. It sets up CORS, logging, recovery, security headers, rate limiting, and other essential middleware.

func Timing

func Timing() echo.MiddlewareFunc

Timing returns a middleware that adds response time headers to HTTP responses. It measures request processing time and adds an X-Response-Time header.

func TraceContext added in v0.3.0

func TraceContext() echo.MiddlewareFunc

TraceContext injects the resolved trace ID and W3C trace context headers from the Echo request/response into the request context, so that outbound HTTP clients can propagate them without depending on Echo.

func WrapHandler added in v0.3.0

func WrapHandler[T any, R any](
	handlerFunc HandlerFunc[T, R],
	binder *RequestBinder,
	cfg *config.Config,
) echo.HandlerFunc

WrapHandler wraps a business logic handler into an Echo-compatible handler. It handles request binding, validation, response formatting, and error handling.

Types

type APIErrorResponse added in v0.3.0

type APIErrorResponse struct {
	Code    string                 `json:"code"`
	Message string                 `json:"message"`
	Details map[string]interface{} `json:"details,omitempty"`
}

APIErrorResponse represents the error portion of an API response.

type APIResponse added in v0.3.0

type APIResponse struct {
	Data  interface{}            `json:"data,omitempty"`
	Error *APIErrorResponse      `json:"error,omitempty"`
	Meta  map[string]interface{} `json:"meta"`
}

APIResponse represents the standardized API response format.

type BadRequestError added in v0.3.0

type BadRequestError struct {
	*BaseAPIError
}

BadRequestError represents bad request errors.

func NewBadRequestError added in v0.3.0

func NewBadRequestError(message string) *BadRequestError

NewBadRequestError creates a new bad request error.

type BaseAPIError added in v0.3.0

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

BaseAPIError provides a basic implementation of IAPIError.

func NewBaseAPIError added in v0.3.0

func NewBaseAPIError(code, message string, httpStatus int) *BaseAPIError

NewBaseAPIError creates a new base API error.

func (*BaseAPIError) Details added in v0.3.0

func (e *BaseAPIError) Details() map[string]any

Details returns additional error details.

func (*BaseAPIError) Error added in v0.3.0

func (e *BaseAPIError) Error() string

Error implements the error interface for BaseAPIError. It returns a concise representation suitable for logs and debugging.

func (*BaseAPIError) ErrorCode added in v0.3.0

func (e *BaseAPIError) ErrorCode() string

ErrorCode returns the error code.

func (*BaseAPIError) HTTPStatus added in v0.3.0

func (e *BaseAPIError) HTTPStatus() int

HTTPStatus returns the HTTP status code.

func (*BaseAPIError) Message added in v0.3.0

func (e *BaseAPIError) Message() string

Message returns the error message.

func (*BaseAPIError) WithDetails added in v0.3.0

func (e *BaseAPIError) WithDetails(key string, value interface{}) *BaseAPIError

WithDetails adds details to the error.

type BusinessLogicError added in v0.3.0

type BusinessLogicError struct {
	*BaseAPIError
}

BusinessLogicError represents domain-specific business logic errors.

func NewBusinessLogicError added in v0.3.0

func NewBusinessLogicError(code, message string) *BusinessLogicError

NewBusinessLogicError creates a new business logic error.

type ConflictError added in v0.3.0

type ConflictError struct {
	*BaseAPIError
}

ConflictError represents resource conflict errors.

func NewConflictError added in v0.3.0

func NewConflictError(message string) *ConflictError

NewConflictError creates a new conflict error.

type FieldError

type FieldError struct {
	Field   string `json:"field"`
	Message string `json:"message"`
	Value   string `json:"value,omitempty"`
}

FieldError represents a validation error for a specific field. It includes the field name, error message, and the invalid value.

type ForbiddenError added in v0.3.0

type ForbiddenError struct {
	*BaseAPIError
}

ForbiddenError represents authorization errors.

func NewForbiddenError added in v0.3.0

func NewForbiddenError(message string) *ForbiddenError

NewForbiddenError creates a new forbidden error.

type HandlerContext added in v0.3.0

type HandlerContext struct {
	Echo   echo.Context
	Config *config.Config
}

HandlerContext provides access to Echo context and additional utilities when needed.

type HandlerFunc added in v0.3.0

type HandlerFunc[T any, R any] func(request T, ctx HandlerContext) (R, IAPIError)

HandlerFunc defines the new handler signature that focuses on business logic.

type HandlerRegistry added in v0.3.0

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

HandlerRegistry manages enhanced handlers and provides registration utilities.

func NewHandlerRegistry added in v0.3.0

func NewHandlerRegistry(cfg *config.Config) *HandlerRegistry

NewHandlerRegistry creates a new handler registry with the given validator and config.

type IAPIError added in v0.3.0

type IAPIError interface {
	ErrorCode() string
	Message() string
	HTTPStatus() int
	Details() map[string]interface{}
}

IAPIError defines the interface for API errors with structured information.

type InternalServerError added in v0.3.0

type InternalServerError struct {
	*BaseAPIError
}

InternalServerError represents internal server errors.

func NewInternalServerError added in v0.3.0

func NewInternalServerError(message string) *InternalServerError

NewInternalServerError creates a new internal server error.

type NoContentResult added in v0.3.0

type NoContentResult struct{}

NoContentResult represents a 204 No Content response without a body

func NoContent added in v0.3.0

func NoContent() NoContentResult

NoContent returns a 204 No Content result without a response body

func (NoContentResult) ResultMeta added in v0.3.0

func (NoContentResult) ResultMeta() (status int, headers http.Header, data any)

ResultMeta implements ResultLike for NoContentResult

type NotFoundError added in v0.3.0

type NotFoundError struct {
	*BaseAPIError
}

NotFoundError represents resource not found errors.

func NewNotFoundError added in v0.3.0

func NewNotFoundError(resource string) *NotFoundError

NewNotFoundError creates a new not found error.

type RequestBinder added in v0.3.0

type RequestBinder struct{}

RequestBinder handles binding request data to structs with validation.

func NewRequestBinder added in v0.3.0

func NewRequestBinder() *RequestBinder

NewRequestBinder creates a new request binder with the given validator.

type Result added in v0.3.0

type Result[R any] struct {
	Data    R
	Status  int
	Headers http.Header
}

Result is a generic success wrapper allowing handlers to customize status and headers while preserving type safety of the response payload.

func Accepted added in v0.3.0

func Accepted[R any](data R) Result[R]

Accepted returns a 202 Accepted Result for the given data

func Created added in v0.3.0

func Created[R any](data R) Result[R]

Created returns a 201 Created Result for the given data

func NewResult added in v0.3.0

func NewResult[R any](status int, data R) Result[R]

NewResult is a convenience constructor for Result.

func (Result[R]) ResultMeta added in v0.3.0

func (r Result[R]) ResultMeta() (status int, headers http.Header, data any)

ResultMeta implements ResultLike for Result[R].

type ResultLike added in v0.3.0

type ResultLike interface {
	ResultMeta() (status int, headers http.Header, data any)
}

ResultLike exposes status, headers, and payload for successful responses.

type Server

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

Server represents an HTTP server instance with Echo framework. It manages server lifecycle, configuration, and request handling.

func New

func New(cfg *config.Config, log logger.Logger) *Server

New creates a new HTTP server instance with the given configuration and logger. It initializes Echo with middlewares, error handling, and health check endpoints.

func (*Server) Echo

func (s *Server) Echo() *echo.Echo

Echo returns the underlying Echo instance for route registration. This allows modules to register their routes with the server.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the HTTP server with the given context. It waits for existing connections to finish within the context timeout.

func (*Server) Start

func (s *Server) Start() error

Start starts the HTTP server and begins accepting requests. It blocks until the server is shut down or encounters an error.

type ServiceUnavailableError added in v0.3.0

type ServiceUnavailableError struct {
	*BaseAPIError
}

ServiceUnavailableError represents service unavailable errors.

func NewServiceUnavailableError added in v0.3.0

func NewServiceUnavailableError(message string) *ServiceUnavailableError

NewServiceUnavailableError creates a new service unavailable error.

type TooManyRequestsError added in v0.3.0

type TooManyRequestsError struct {
	*BaseAPIError
}

TooManyRequestsError represents rate limiting errors.

func NewTooManyRequestsError added in v0.3.0

func NewTooManyRequestsError(message string) *TooManyRequestsError

NewTooManyRequestsError creates a new too many requests error.

type UnauthorizedError added in v0.3.0

type UnauthorizedError struct {
	*BaseAPIError
}

UnauthorizedError represents authentication errors.

func NewUnauthorizedError added in v0.3.0

func NewUnauthorizedError(message string) *UnauthorizedError

NewUnauthorizedError creates a new unauthorized error.

type ValidationError

type ValidationError struct {
	Errors []FieldError `json:"errors"`
}

ValidationError wraps validation errors with better messages and structured field errors. It provides a standardized format for validation error responses.

func NewValidationError

func NewValidationError(errs validator.ValidationErrors) *ValidationError

NewValidationError creates a ValidationError from go-playground/validator errors. It converts the errors into a more user-friendly format with descriptive messages.

func (*ValidationError) Error

func (ve *ValidationError) Error() string

type Validator

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

Validator wraps go-playground/validator with custom validation logic. It provides request validation functionality with custom validators.

func NewValidator

func NewValidator() *Validator

NewValidator creates a new Validator instance with custom validation rules registered.

func (*Validator) GetValidator added in v0.3.0

func (v *Validator) GetValidator() *validator.Validate

GetValidator returns the underlying validator instance.

func (*Validator) Validate

func (v *Validator) Validate(i interface{}) error

Validate performs validation on the provided struct and returns any validation errors.

Jump to

Keyboard shortcuts

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