ginkgo

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2025 License: MIT Imports: 23 Imported by: 0

README

ginkgo

Documentation

Index

Constants

View Source
const (
	ErrMissingToken = "missing token"
	ErrInvalidToken = "invalid token"
	ErrUserNotFound = "user not found"
	ErrNoPermission = "user does not have the required permission"

	ErrTypeUnauthorized = "Unauthorized"
	ErrTypeForbidden    = "Forbidden"
)

Variables

This section is empty.

Functions

func BindRequest

func BindRequest[T any](ctx *gin.Context, bindType binding.Binding) (T, error)

BindRequest binds the incoming HTTP request to a struct of type T using the specified binding type. It supports various Gin binding types such as JSON, XML, Query, etc. Returns the bound struct or an error if binding fails.

func GetAndParseFromContext

func GetAndParseFromContext[T any](ctx *gin.Context, key string) (T, error)

GetAndParseFromContext retrieves a string value from the Gin context and parses it to type T. It combines GetFromContext and Parse operations in a single function call. Returns the parsed value or an error if the key doesn't exist or parsing fails.

func GetFromContext

func GetFromContext[T any](ctx *gin.Context, key string) (T, error)

GetFromContext retrieves a value from the Gin context and type-asserts it to type T. Returns the typed value or an error if the key does not exist or type assertion fails. Useful for retrieving typed data stored in context by middleware.

func GetPathParam

func GetPathParam[T any](ctx *gin.Context, key string) (T, bool, error)

GetPathParam extracts and parses a path parameter from the Gin context. It returns the parsed value of type T, a boolean indicating if the parameter exists, and an error if parsing fails. If the parameter does not exist, it returns the zero value with false. Supports parsing to string, int, bool, and UUID types.

func GetRequiredPathParam

func GetRequiredPathParam[T any](ctx *gin.Context, key string) (T, error)

GetRequiredPathParam extracts and parses a required path parameter from the Gin context. It returns the parsed value of type T or an error if the parameter is missing or parsing fails. Unlike GetPathParam, this function treats missing parameters as an error condition.

Types

type HttpServer

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

func NewHttpServer

func NewHttpServer(srv *http.Server, timeout time.Duration, logger ezutil.Logger, shutdownFunc func() error) *HttpServer

func (*HttpServer) ServeGracefully

func (hs *HttpServer) ServeGracefully()

ServeGracefully starts the HTTP server and handles graceful shutdown

type JSONResponse

type JSONResponse struct {
	Message    string     `json:"message"`
	Data       any        `json:"data,omitzero"`
	Errors     error      `json:"errors,omitempty"`
	Pagination Pagination `json:"pagination,omitzero"`
}

JSONResponse represents a standardized HTTP JSON response structure. It can include a message, data payload, error information, and pagination metadata.

func NewErrorResponse

func NewErrorResponse(err error) JSONResponse

NewErrorResponse creates a JSONResponse for error cases. It sets the message to the error text and populates the Errors field.

func NewResponse

func NewResponse(message string) JSONResponse

NewResponse creates a basic JSONResponse with the specified message. Additional data, errors, or pagination can be added using the With* methods.

func (JSONResponse) WithData

func (jr JSONResponse) WithData(data any) JSONResponse

WithData adds a data payload to the JSONResponse. Returns a new JSONResponse with the Data field populated.

func (JSONResponse) WithError

func (jr JSONResponse) WithError(err error) JSONResponse

WithError adds error information to the JSONResponse. Returns a new JSONResponse with the Errors field populated.

func (JSONResponse) WithPagination

func (jr JSONResponse) WithPagination(queryOptions QueryOptions, totalData int) JSONResponse

WithPagination calculates and adds pagination metadata to the JSONResponse. It computes total pages and next/previous flags based on query options and total data count. Returns a new JSONResponse with pagination metadata included.

type MiddlewareProvider

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

func NewMiddlewareProvider

func NewMiddlewareProvider(logger ezutil.Logger) *MiddlewareProvider

func (*MiddlewareProvider) NewAuthMiddleware

func (mp *MiddlewareProvider) NewAuthMiddleware(
	authStrategy string,
	tokenCheckFunc func(ctx *gin.Context, token string) (bool, map[string]any, error),
) gin.HandlerFunc

NewAuthMiddleware creates an authentication middleware for Gin. It extracts a token using the given strategy (e.g., "header" or "cookie") via internal.ExtractToken, calls tokenCheckFunc to validate the token and retrieve user data, stores user data in the Gin context, and aborts the request on errors. Returns a Gin HandlerFunc for authentication handling.

func (*MiddlewareProvider) NewCorsMiddleware

func (mp *MiddlewareProvider) NewCorsMiddleware(corsConfig *cors.Config) gin.HandlerFunc

NewCorsMiddleware creates a CORS middleware for Gin with the provided configuration. If corsConfig is nil, default settings are used (via cors.Default()). The middleware validates the configuration and logs a fatal error if invalid. Returns a Gin HandlerFunc to handle CORS according to the specified config.

func (*MiddlewareProvider) NewErrorMiddleware

func (mp *MiddlewareProvider) NewErrorMiddleware() gin.HandlerFunc

func (*MiddlewareProvider) NewLoggingMiddleware added in v0.2.0

func (mp *MiddlewareProvider) NewLoggingMiddleware() gin.HandlerFunc

func (*MiddlewareProvider) NewPermissionMiddleware

func (mp *MiddlewareProvider) NewPermissionMiddleware(
	roleContextKey string,
	requiredPermission string,
	permissionMap map[string][]string,
) gin.HandlerFunc

NewPermissionMiddleware creates a permission-checking middleware for Gin. It retrieves the user role from context using the provided roleContextKey, checks if the role exists in permissionMap and includes the requiredPermission, and aborts the request with a ForbiddenError if permission is missing. Returns a Gin HandlerFunc for permission enforcement.

type Pagination

type Pagination struct {
	TotalData   int  `json:"totalData"`
	CurrentPage int  `json:"currentPage"`
	TotalPages  int  `json:"totalPages"`
	HasNextPage bool `json:"hasNextPage"`
	HasPrevPage bool `json:"hasPrevPage"`
}

Pagination contains metadata about paginated results. It provides information about the current page, total pages, and navigation flags.

func (Pagination) IsZero

func (p Pagination) IsZero() bool

IsZero checks if all pagination fields are at their zero values. Returns true if the pagination data is uninitialized or empty.

type QueryOptions

type QueryOptions struct {
	Page  int `query:"page" binding:"required,min=1"`
	Limit int `query:"limit" binding:"required,min=1"`
}

QueryOptions represents common pagination query parameters for HTTP requests. It includes validation tags to ensure proper values for page and limit parameters.

Jump to

Keyboard shortcuts

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