Documentation
¶
Index ¶
- Constants
- Variables
- func ArrContains[T string | int | float32](arr []T, val T) bool
- func FastJWTAuth(next fasthttp.RequestHandler) fasthttp.RequestHandler
- func FastStaticAuth(next fasthttp.RequestHandler) fasthttp.RequestHandler
- func GenerateQueryComponenFromStruct(model interface{}, skips []string) (string, []interface{}, string)
- func GetDateNowStringWithTimezone() string
- func GetDateTimeNowStringWithFormat(layout string) string
- func GetDateTimeNowStringWithTimezone() string
- func GetStructKey(field reflect.StructField) string
- func GetStructValue(value reflect.Value) interface{}
- func GetTimeNowStringWithTimezone() string
- func GetTimeNowWithTimezone() time.Time
- func InitHandler(router http.Handler) http.Handler
- func MethodNotAllowedHandler(w http.ResponseWriter, r *http.Request)
- func PanicHandler(next http.Handler) http.Handler
- func ParseDate(dateStrInput string) (string, error)
- func ParseToDateOnly(date string) string
- func ParseToTimeOnly(t string) string
- func RegisterMiddleware[T any](app *App, key string, middlewareHandler T)
- func ReleaseRequest(req *Request)
- func ReleaseResponse(resp *Response)
- func ReleaseWrittenResponseWriter(w *WrittenResponseWriter)
- func RouteNotFoundHandler(w http.ResponseWriter, r *http.Request)
- func WaitTermSig(ctx context.Context, handler func(context.Context) error) <-chan struct{}
- func WriteJson(w http.ResponseWriter, data interface{})
- type App
- func (app *App) AddController(ctrl Controller)
- func (app *App) AddControllers(ctrls Controllers)
- func (app *App) AddGlobalMiddleware(handlers ...func(http.Handler) http.Handler)
- func (app *App) AddScheduler(pattern string, handler cron.HandlerFunc)
- func (app *App) DB() database.ISQL
- func (app *App) Init()
- func (app *App) RegisterMiddlewareFunc(key string, middlewareHandler func(http.Handler) http.Handler)
- func (app *App) SSE() sse.Events
- func (app *App) SetVersion(version string)
- func (app *App) Start() error
- func (app *App) Trx() database.Transactions
- func (app *App) WrapScheduler(wrapper cron.Wrapper)
- func (app *App) WrapToApp(wrapper Wrapper)
- type Apps
- type Controller
- type ControllerConfig
- type ControllerImpl
- type Controllers
- type ErrorOption
- type FastController
- type FastControllerConfig
- type FastDirectHandler
- type FastHandler
- type FastHttpApp
- type FastKeyExtractor
- type FastMiddleware
- type FastRateLimiterOption
- type FastRequest
- func (r *FastRequest) Ctx() *fasthttp.RequestCtx
- func (r *FastRequest) GetBody(dest interface{}) error
- func (r *FastRequest) GetFile(key string) (interface{}, error)
- func (r *FastRequest) GetHeaders(dest interface{}) error
- func (r *FastRequest) GetParam(key string, defaultValue ...string) string
- func (r *FastRequest) GetQuery(dest interface{}) error
- func (r *FastRequest) Header(key string) string
- type FastResponse
- type FastRoute
- type Handler
- type HttpError
- func BadRequest(message, code string) *HttpError
- func Forbidden(message, code string) *HttpError
- func InternalServerError(message, code string) *HttpError
- func MethodNotAllowed(message, code string) *HttpError
- func NewErr(opts ...ErrorOption) *HttpError
- func NotFound(message, code string) *HttpError
- func TooManyRequest(message, code string) *HttpError
- func Unauthorized(message, code string) *HttpError
- func UnprocessableEntity(message, code string) *HttpError
- type Map
- type Options
- func ReadTimeout(readTimeout int) Options
- func WithAPITimeout(apiTimeout int) Options
- func WithAppPort(port int) Options
- func WithCronJob(timezone ...string) Options
- func WithFastHttp() Options
- func WithGlobalMiddleware(handlers ...func(http.Handler) http.Handler) Options
- func WithNewRelic() Options
- func WithOTel() Options
- func WithPprof(enabled bool) Options
- func WithSSE() Options
- func WithSkipLogPaths(paths ...string) Options
- func WithTimezone(timezone string) Options
- func WriteTimeout(writeTimeout int) Options
- type Request
- type Response
- func (resp *Response) Send(w http.ResponseWriter)
- func (resp *Response) SentNotif(ctx contextpkg.Context, err *HttpError, r *http.Request, traceId string)
- func (resp *Response) SetCustomHeader(key, value string) *Response
- func (resp *Response) SetData(data any, isPaginate ...bool) *Response
- func (resp *Response) SetError(err error) *Response
- func (resp *Response) SetFileDownload(data []byte, fileName string, contentType string) *Response
- func (resp *Response) SetHTTPError(err *HttpError) *Response
- func (resp *Response) SetMessage(msg string) *Response
- func (resp *Response) SetStatusCode(statusCode int) *Response
- type ResponseRecorder
- type Route
- type RouteOption
- type StringMap
- type ValidationError
- type Wrapper
- type WrittenResponseWriter
Constants ¶
const ( DateFormat = "2006-01-02" TimeFormat = "15:04:05" )
Variables ¶
var TimezoneLocation *time.Location
Functions ¶
func FastJWTAuth ¶ added in v2.41.0
func FastJWTAuth(next fasthttp.RequestHandler) fasthttp.RequestHandler
func FastStaticAuth ¶ added in v2.41.0
func FastStaticAuth(next fasthttp.RequestHandler) fasthttp.RequestHandler
func GetDateNowStringWithTimezone ¶ added in v2.24.0
func GetDateNowStringWithTimezone() string
func GetDateTimeNowStringWithFormat ¶ added in v2.24.0
func GetDateTimeNowStringWithTimezone ¶ added in v2.24.0
func GetDateTimeNowStringWithTimezone() string
func GetStructKey ¶
func GetStructKey(field reflect.StructField) string
func GetStructValue ¶
func GetTimeNowStringWithTimezone ¶ added in v2.24.0
func GetTimeNowStringWithTimezone() string
func GetTimeNowWithTimezone ¶ added in v2.24.0
func MethodNotAllowedHandler ¶
func MethodNotAllowedHandler(w http.ResponseWriter, r *http.Request)
func ParseDate ¶ added in v2.24.0
ParseDate takes a date string and tries to parse it into the standard format "YYYY-MM-DD".
func ParseToDateOnly ¶ added in v2.24.0
func ParseToTimeOnly ¶ added in v2.24.0
func RegisterMiddleware ¶ added in v2.40.0
func ReleaseRequest ¶ added in v2.41.0
func ReleaseRequest(req *Request)
ReleaseRequest resets and returns a Request to the pool.
func ReleaseResponse ¶ added in v2.41.0
func ReleaseResponse(resp *Response)
ReleaseResponse resets the Response and returns it to the sync.Pool. Must be called after Send() to avoid resource leaks.
func ReleaseWrittenResponseWriter ¶ added in v2.41.0
func ReleaseWrittenResponseWriter(w *WrittenResponseWriter)
ReleaseWrittenResponseWriter resets and returns a WrittenResponseWriter to the pool.
func RouteNotFoundHandler ¶
func RouteNotFoundHandler(w http.ResponseWriter, r *http.Request)
func WaitTermSig ¶ added in v2.36.0
func WriteJson ¶
func WriteJson(w http.ResponseWriter, data interface{})
Types ¶
type App ¶
type App struct {
Http *chi.Mux
*server.Config
TotalEndpoints int
// contains filtered or unexported fields
}
func (*App) AddController ¶
func (app *App) AddController(ctrl Controller)
func (*App) AddControllers ¶ added in v2.19.0
func (app *App) AddControllers(ctrls Controllers)
func (*App) AddGlobalMiddleware ¶ added in v2.40.0
AddGlobalMiddleware appends middleware(s) to be applied to all endpoints. Use this for middlewares that depend on resources initialized after NewApp() (e.g. repository-dependent middlewares wired in loadModules). The middlewares are stored internally and applied lazily when the first route is registered, avoiding the chi restriction that middlewares must be defined before routes.
func (*App) AddScheduler ¶ added in v2.8.1
func (app *App) AddScheduler(pattern string, handler cron.HandlerFunc)
func (*App) RegisterMiddlewareFunc ¶ added in v2.40.0
func (*App) SetVersion ¶ added in v2.23.0
func (*App) Trx ¶ added in v2.13.2
func (app *App) Trx() database.Transactions
func (*App) WrapScheduler ¶ added in v2.8.7
type Controller ¶
type Controller interface {
GetConfig() ControllerConfig
}
type ControllerConfig ¶
type ControllerImpl ¶
type ControllerImpl struct {
// contains filtered or unexported fields
}
func NewControllerImpl ¶ added in v2.40.1
func NewControllerImpl() *ControllerImpl
func (*ControllerImpl) JoinMiddleware ¶
func (*ControllerImpl) SetRegisteredMiddlewares ¶ added in v2.40.0
func (ctrl *ControllerImpl) SetRegisteredMiddlewares(m map[string]any)
SetRegisteredMiddlewares is called by App.AddController to inject the app-level middleware registry.
func (*ControllerImpl) UseMiddleware ¶ added in v2.40.0
UseMiddleware retrieves a registered middleware by key. Returns nil if the key is not found — caller should handle nil check or skip.
type Controllers ¶ added in v2.19.0
type Controllers interface {
Register() []Controller
}
type ErrorOption ¶
type ErrorOption func(*HttpError)
func WithErrorCallerPath ¶ added in v2.9.7
func WithErrorCallerPath(callerPath string) ErrorOption
func WithErrorCode ¶ added in v2.9.6
func WithErrorCode(code string) ErrorOption
func WithErrorData ¶ added in v2.9.6
func WithErrorData(data interface{}) ErrorOption
func WithErrorMessage ¶ added in v2.9.6
func WithErrorMessage(message string) ErrorOption
func WithErrorStatus ¶ added in v2.9.6
func WithErrorStatus(status int) ErrorOption
func WithTraceId ¶ added in v2.25.0
func WithTraceId(traceId string) ErrorOption
type FastController ¶ added in v2.41.0
type FastController interface {
GetConfig() FastControllerConfig
}
FastController is the controller interface for the fasthttp-native path.
type FastControllerConfig ¶ added in v2.41.0
type FastControllerConfig struct {
Path string
Routes []FastRoute
Middlewares []FastMiddleware
}
FastControllerConfig holds controller configuration.
type FastDirectHandler ¶ added in v2.41.0
type FastDirectHandler func(req *FastRequest) *FastResponse
FastDirectHandler is the optimized handler type that writes directly to the fasthttp.RequestCtx via FastResponse. No intermediate Response struct, no json.Marshal for simple responses. This is the fastest path.
type FastHandler ¶ added in v2.41.0
type FastHandler func(FastRequest, context.Context) *Response
FastHandler is the handler function type for the fasthttp-native path. It receives a FastRequest (with methods for params/query/body/headers) and a context.Context, and returns a *Response — same signature as chi Handler. This is the compatibility path that still goes through Response + json.Marshal.
type FastHttpApp ¶ added in v2.41.0
type FastHttpApp struct {
TotalEndpoints int
// contains filtered or unexported fields
}
FastHttpApp is a native fasthttp application that bypasses net/http entirely. It provides the same Phastos API surface (Request/Response, middleware chain, controller pattern) but with zero net/http overhead.
func NewFastHttpApp ¶ added in v2.41.0
func NewFastHttpApp() *FastHttpApp
NewFastHttpApp creates a new native fasthttp application.
func (*FastHttpApp) AddController ¶ added in v2.41.0
func (app *FastHttpApp) AddController(ctrl FastController)
AddController registers all routes from a FastController.
func (*FastHttpApp) AddGlobalMiddleware ¶ added in v2.41.0
func (app *FastHttpApp) AddGlobalMiddleware(handlers ...FastMiddleware)
AddGlobalMiddleware adds middleware(s) that run on every request.
func (*FastHttpApp) Handler ¶ added in v2.41.0
func (app *FastHttpApp) Handler() fasthttp.RequestHandler
Handler returns the composed fasthttp.RequestHandler with all middlewares applied. Built-in middlewares (init, panic, logger) are fused into a single handler to eliminate 3 indirect function calls per request (~60-90ns savings).
func (*FastHttpApp) Init ¶ added in v2.41.0
func (app *FastHttpApp) Init()
Init initializes the fasthttp router.
func (*FastHttpApp) RegisterMiddlewareFunc ¶ added in v2.41.0
func (app *FastHttpApp) RegisterMiddlewareFunc(key string, mw FastMiddleware)
RegisterMiddlewareFunc registers a middleware by key for later use by controllers.
type FastKeyExtractor ¶ added in v2.41.0
type FastKeyExtractor func(ctx *fasthttp.RequestCtx) string
type FastMiddleware ¶ added in v2.41.0
type FastMiddleware func(fasthttp.RequestHandler) fasthttp.RequestHandler
FastMiddleware is the middleware type for the fasthttp-native path.
func FastNewRateLimiter ¶ added in v2.41.0
func FastNewRateLimiter(opts ...FastRateLimiterOption) FastMiddleware
FastNewRateLimiter returns a fasthttp middleware that rate-limits requests using a token-bucket algorithm per bucket key (default = IP address).
type FastRateLimiterOption ¶ added in v2.41.0
type FastRateLimiterOption func(*fastRateLimiter)
type FastRequest ¶ added in v2.41.0
type FastRequest struct {
// contains filtered or unexported fields
}
FastRequest is a zero-allocation request wrapper for fasthttp. Instead of closures (like the chi Request), it stores a pointer to the fasthttp.RequestCtx and provides methods that access it directly. This eliminates 5 closure allocations per request.
func (*FastRequest) Ctx ¶ added in v2.41.0
func (r *FastRequest) Ctx() *fasthttp.RequestCtx
Ctx returns the underlying fasthttp.RequestCtx for direct access. This enables FastDirectHandler to create FastResponse without additional indirection.
func (*FastRequest) GetBody ¶ added in v2.41.0
func (r *FastRequest) GetBody(dest interface{}) error
GetBody decodes the request body into a struct based on Content-Type.
func (*FastRequest) GetFile ¶ added in v2.41.0
func (r *FastRequest) GetFile(key string) (interface{}, error)
GetFile returns a multipart file by key.
func (*FastRequest) GetHeaders ¶ added in v2.41.0
func (r *FastRequest) GetHeaders(dest interface{}) error
GetHeaders decodes request headers into a struct using gorilla/schema.
func (*FastRequest) GetParam ¶ added in v2.41.0
func (r *FastRequest) GetParam(key string, defaultValue ...string) string
GetParam returns a path parameter by key. For fasthttp, path params are stored as UserValues set by the router.
func (*FastRequest) GetQuery ¶ added in v2.41.0
func (r *FastRequest) GetQuery(dest interface{}) error
GetQuery decodes query parameters into a struct using gorilla/schema.
func (*FastRequest) Header ¶ added in v2.41.0
func (r *FastRequest) Header(key string) string
Header returns a specific request header value.
type FastResponse ¶ added in v2.41.0
type FastResponse struct {
// contains filtered or unexported fields
}
FastResponse writes directly to fasthttp.RequestCtx with zero intermediate allocations. For simple message/data responses it avoids json.Marshal by using fasthttp's built-in body writer.
func NewFastResponse ¶ added in v2.41.0
func NewFastResponse(ctx *fasthttp.RequestCtx) *FastResponse
NewFastResponse creates a FastResponse that writes directly to the ctx. Uses sync.Pool to avoid heap allocation per request.
func (*FastResponse) SetData ¶ added in v2.41.0
func (fr *FastResponse) SetData(data any) *FastResponse
SetData writes a JSON response with arbitrary data using json.Marshal. This is the slower path but still avoids the Response struct pool overhead.
func (*FastResponse) SetError ¶ added in v2.41.0
func (fr *FastResponse) SetError(err *HttpError) *FastResponse
SetError writes an error JSON response.
func (*FastResponse) SetMessage ¶ added in v2.41.0
func (fr *FastResponse) SetMessage(msg string) *FastResponse
SetMessage writes a JSON {"message":"..."} response directly to the ctx. This is the fast path — no json.Marshal, no map allocation, no intermediate buffer. Uses SetBodyString to write the complete body in a single operation.
func (*FastResponse) SetStatusCode ¶ added in v2.41.0
func (fr *FastResponse) SetStatusCode(code int) *FastResponse
SetStatusCode sets the HTTP status code.
type FastRoute ¶ added in v2.41.0
type FastRoute struct {
Method string
Path string
Handler FastHandler // compatibility path (returns *Response)
DirectHandler FastDirectHandler // optimized path (returns *FastResponse, writes directly)
Version int
Middlewares []FastMiddleware
}
FastRoute holds route configuration.
func (*FastRoute) GetVersionedPath ¶ added in v2.41.0
type HttpError ¶
type HttpError struct {
Message string `json:"message"`
Code string `json:"code"`
Status int `json:"-"`
TraceId string `json:"trace_id"`
Data interface{} `json:"data,omitempty"`
CallerPath string `json:"caller_path,omitempty"`
}
func BadRequest ¶
func InternalServerError ¶
func MethodNotAllowed ¶
func NewErr ¶
func NewErr(opts ...ErrorOption) *HttpError
func TooManyRequest ¶
func Unauthorized ¶
func UnprocessableEntity ¶
func (*HttpError) Write ¶
func (e *HttpError) Write(w http.ResponseWriter)
type Options ¶
type Options func(api *App)
func ReadTimeout ¶
func WithAPITimeout ¶
func WithAppPort ¶
func WithCronJob ¶ added in v2.8.0
func WithFastHttp ¶ added in v2.41.0
func WithFastHttp() Options
func WithGlobalMiddleware ¶ added in v2.40.0
WithGlobalMiddleware registers middleware(s) that will be applied to ALL endpoints (both authenticated and unauthenticated). These run after the built-in middlewares (request logger, recoverer, panic handler) but before any route-specific middleware. Use this in NewApp() for middlewares that have no external dependencies.
func WithNewRelic ¶ added in v2.20.0
func WithNewRelic() Options
func WithSkipLogPaths ¶ added in v2.41.0
WithSkipLogPaths configures paths that skip the requestLogger middleware. The /ping path is always skipped. Add additional paths (e.g. /health, /metrics) to avoid per-request logging overhead for lightweight endpoints.
func WithTimezone ¶ added in v2.24.0
func WriteTimeout ¶
type Response ¶
type Response struct {
Message string `json:"message,omitempty"`
Data any `json:"data,omitempty"`
Err error `json:"error,omitempty"`
TraceId string `json:"trace_id"`
InternalError *HttpError `json:"-"`
MetaData *database.ResponseMetaData `json:"metadata,omitempty"`
// contains filtered or unexported fields
}
func NewResponse ¶
func NewResponse() *Response
NewResponse creates a new Response from the sync.Pool. After calling Response.Send(w), call ReleaseResponse(resp) to return it to the pool.
func (*Response) Send ¶ added in v2.3.9
func (resp *Response) Send(w http.ResponseWriter)
func (*Response) SetCustomHeader ¶ added in v2.39.2
func (*Response) SetFileDownload ¶ added in v2.38.0
SetFileDownload configures the response to send binary file data as a download instead of the default JSON response. Content-Type and Content-Disposition headers are set automatically.
Example with BulkGenerator:
zipBytes, results, err := bulk.GenerateZip("reports.zip")
if err != nil {
return api.NewResponse().SetError(err)
}
return api.NewResponse().SetFileDownload(zipBytes, "reports.zip", "application/zip")
func (*Response) SetHTTPError ¶
func (*Response) SetMessage ¶
func (*Response) SetStatusCode ¶ added in v2.17.5
type ResponseRecorder ¶ added in v2.37.4
type ResponseRecorder struct {
http.ResponseWriter
StatusCode int
}
func NewResponseRecorder ¶ added in v2.37.4
func NewResponseRecorder(w http.ResponseWriter) *ResponseRecorder
func (*ResponseRecorder) WriteHeader ¶ added in v2.37.4
func (r *ResponseRecorder) WriteHeader(status int)
WriteHeader overrides the default WriteHeader to store the status code.
type Route ¶
type Route struct {
Method string
Path string
Handler Handler
Version int
Middlewares *[]func(http.Handler) http.Handler
}
func (*Route) GetVersionedPath ¶
type RouteOption ¶
type RouteOption func(*Route)
func WithMiddleware ¶
func WithMiddleware(handlers ...func(http.Handler) http.Handler) RouteOption
func WithPath ¶
func WithPath(path string) RouteOption
func WithVersion ¶
func WithVersion(version int) RouteOption
type ValidationError ¶
type ValidationError struct {
Field string `json:"field"`
Tag string `json:"tag"`
Value string `json:"value"`
}
func ValidateStruct ¶
func ValidateStruct(data interface{}) []*ValidationError
type WrittenResponseWriter ¶
type WrittenResponseWriter struct {
http.ResponseWriter
// contains filtered or unexported fields
}
func (*WrittenResponseWriter) Flush ¶ added in v2.38.0
func (w *WrittenResponseWriter) Flush()
Flush implements http.Flusher interface for streaming responses (SSE, WebSocket, etc.)
func (*WrittenResponseWriter) WriteHeader ¶
func (w *WrittenResponseWriter) WriteHeader(status int)
func (*WrittenResponseWriter) Written ¶
func (w *WrittenResponseWriter) Written() bool