gocontroller

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Apr 12, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const RequestIDHeader = "X-Request-ID"
View Source
const Version = "v1.2.0"

Version is the current library version.

Variables

View Source
var ErrNotFound = errors.New("route not found")
View Source
var ErrValidation = errors.New("validation failed")

Functions

func NotFoundHTMLOrJSON added in v1.0.1

func NotFoundHTMLOrJSON(notFoundHTMLFile string, jsonMessage string) http.HandlerFunc

NotFoundHTMLOrJSON serves an HTML 404 page for browser requests and JSON for APIs.

func ParseDTO

func ParseDTO[T any](ctx *Context) (T, error)

ParseDTO decodes JSON body into a typed DTO and runs validation.

func RegisterGeneratedControllerMetadata

func RegisterGeneratedControllerMetadata(controllerPtr any, meta ControllerMetadata)

RegisterGeneratedControllerMetadata is used by generated code.

func ServePage added in v1.0.1

func ServePage(publicDir, pageFile string) http.HandlerFunc

ServePage returns a handler that serves a single static page from publicDir.

func SetDefaultValidator

func SetDefaultValidator(v Validator)

SetDefaultValidator sets the process-wide default validator used by Validate and new routers.

func Validate

func Validate(dto any) error

func WebAPIHandler added in v1.0.1

func WebAPIHandler(web http.Handler, api http.Handler, opts HybridOptions) http.Handler

WebAPIHandler composes web and api handlers, reducing manual path-switch boilerplate.

Types

type APIError added in v1.1.0

type APIError struct {
	StatusCode int
	Code       string
	Message    string
	Details    any
	Cause      error
}

APIError is a standardized error model for HTTP responses.

func BadRequestError added in v1.1.0

func BadRequestError(message string) *APIError

func ConflictError added in v1.1.0

func ConflictError(message string) *APIError

func ForbiddenError added in v1.1.0

func ForbiddenError(message string) *APIError

func InternalError added in v1.1.0

func InternalError(message string) *APIError

func NewAPIError added in v1.1.0

func NewAPIError(status int, code, message string) *APIError

func NotFoundError added in v1.1.0

func NotFoundError(message string) *APIError

func UnauthorizedError added in v1.1.0

func UnauthorizedError(message string) *APIError

func (*APIError) Error added in v1.1.0

func (e *APIError) Error() string

func (*APIError) Unwrap added in v1.1.0

func (e *APIError) Unwrap() error

type App

type App struct {
	Router    *Router
	Container *Container
}

func NewApp

func NewApp(root *Module) (*App, error)

func (*App) Handler

func (a *App) Handler() http.Handler

Handler exposes the application router as an http.Handler. This makes it easy to mount in Gin/Echo/Fiber adapter wrappers.

func (*App) Listen

func (a *App) Listen(addr string) error

func (*App) NewHTTPServer added in v1.1.0

func (a *App) NewHTTPServer(opts ServerOptions) *http.Server

func (*App) Run added in v1.1.0

func (a *App) Run(ctx context.Context, opts ServerOptions) error

Run starts the HTTP server and gracefully shuts down on context cancellation.

func (*App) SetValidator

func (a *App) SetValidator(v Validator)

SetValidator overrides the app/router validator for request DTO validation.

func (*App) Validator

func (a *App) Validator() Validator

Validator returns the validator used by the app/router.

type CORSConfig added in v1.2.0

type CORSConfig struct {
	AllowOrigin  string
	AllowMethods []string
	AllowHeaders []string
	MaxAge       int
}

type Container

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

func NewContainer

func NewContainer() *Container

func (*Container) MustResolve

func (c *Container) MustResolve(target any)

func (*Container) Provide

func (c *Container) Provide(value any) error

func (*Container) Resolve

func (c *Container) Resolve(target any) error

type Context

type Context struct {
	ResponseWriter http.ResponseWriter
	Request        *http.Request
	Params         map[string]string
	Values         map[string]any
	// contains filtered or unexported fields
}

Context carries request/response helpers for handlers and middleware.

func (*Context) BadRequest added in v1.0.1

func (c *Context) BadRequest(message string) error

func (*Context) BindJSON

func (c *Context) BindJSON(dto any) error

func (*Context) Conflict added in v1.0.1

func (c *Context) Conflict(message string) error

func (*Context) Created added in v1.0.1

func (c *Context) Created(data any) error

func (*Context) Error added in v1.0.1

func (c *Context) Error(status int, message string) error

Error returns a standard error envelope: {"success": false, "error": ...}.

func (*Context) Forbidden added in v1.0.1

func (c *Context) Forbidden(message string) error

func (*Context) Get

func (c *Context) Get(key string) (any, bool)

func (*Context) InternalError added in v1.0.1

func (c *Context) InternalError(message string) error

func (*Context) JSON

func (c *Context) JSON(status int, body any) error

func (*Context) NoContent added in v1.0.1

func (c *Context) NoContent() error

func (*Context) NotFound added in v1.0.1

func (c *Context) NotFound(message string) error

func (*Context) OK added in v1.0.1

func (c *Context) OK(data any) error

func (*Context) Param

func (c *Context) Param(name string) string

func (*Context) RequestID added in v1.1.0

func (c *Context) RequestID() string

func (*Context) Set

func (c *Context) Set(key string, value any)

func (*Context) Success added in v1.0.1

func (c *Context) Success(status int, data any) error

Success returns a standard success envelope: {"success": true, "data": ...}.

func (*Context) Text

func (c *Context) Text(status int, value string) error

func (*Context) Unauthorized added in v1.0.1

func (c *Context) Unauthorized(message string) error

type Controller

type Controller interface {
	RegisterRoutes(*RouteGroup)
}

type ControllerMetadata

type ControllerMetadata struct {
	Prefix     string
	Middleware []Middleware
	Routes     []RouteMetadata
}

ControllerMetadata is decorator-like route metadata for a controller.

type DecoratedController

type DecoratedController interface {
	ControllerMetadata() ControllerMetadata
}

DecoratedController declares controller metadata for auto route binding.

type GoPlaygroundValidator

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

GoPlaygroundValidator uses github.com/go-playground/validator/v10.

func NewGoPlaygroundValidator

func NewGoPlaygroundValidator() *GoPlaygroundValidator

func (*GoPlaygroundValidator) Validate

func (g *GoPlaygroundValidator) Validate(dto any) error

type HTTPError

type HTTPError struct {
	StatusCode int
	Message    string
}

func NewHTTPError

func NewHTTPError(statusCode int, message string) *HTTPError

func (*HTTPError) Error

func (e *HTTPError) Error() string

type HandlerFunc

type HandlerFunc func(*Context) error

type HybridOptions added in v1.0.1

type HybridOptions struct {
	WebExactPaths              []string
	WebPathPrefixes            []string
	TreatSingleSegmentGETAsWeb bool
}

HybridOptions controls how WebAPIHandler routes traffic to web or api handlers.

type Middleware

type Middleware func(HandlerFunc) HandlerFunc

func AdaptHTTPMiddleware added in v1.0.1

func AdaptHTTPMiddleware(httpMW func(http.Handler) http.Handler) Middleware

AdaptHTTPMiddleware adapts a standard net/http middleware into gocontroller middleware.

func CORS added in v1.2.0

func CORS(config CORSConfig) Middleware

CORS applies a basic CORS policy and handles OPTIONS preflight.

func Recovery added in v1.1.0

func Recovery(config RecoveryConfig) Middleware

Recovery catches panics and returns a standardized 500 error response.

func RequestID added in v1.1.0

func RequestID() Middleware

RequestID injects a request id into Context and response header.

func RequestLogger added in v1.0.1

func RequestLogger() Middleware

RequestLogger logs method, path, status time around each request.

func SecurityHeaders added in v1.2.0

func SecurityHeaders() Middleware

SecurityHeaders adds common hardening headers to responses.

type Module

type Module struct {
	Name        string
	Prefix      string
	Providers   []any
	Controllers []any
	Imports     []*Module
	Middleware  []Middleware
}

Module models a NestJS-like module graph.

type RecoveryConfig added in v1.1.0

type RecoveryConfig struct {
	IncludeStack bool
	Logf         func(format string, args ...any)
}

type RouteGroup

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

func (*RouteGroup) DELETE

func (g *RouteGroup) DELETE(path string, handler HandlerFunc, middleware ...Middleware)

func (*RouteGroup) GET

func (g *RouteGroup) GET(path string, handler HandlerFunc, middleware ...Middleware)

func (*RouteGroup) Group

func (g *RouteGroup) Group(prefix string, middleware ...Middleware) *RouteGroup

func (*RouteGroup) OPTIONS

func (g *RouteGroup) OPTIONS(path string, handler HandlerFunc, middleware ...Middleware)

func (*RouteGroup) PATCH

func (g *RouteGroup) PATCH(path string, handler HandlerFunc, middleware ...Middleware)

func (*RouteGroup) POST

func (g *RouteGroup) POST(path string, handler HandlerFunc, middleware ...Middleware)

func (*RouteGroup) PUT

func (g *RouteGroup) PUT(path string, handler HandlerFunc, middleware ...Middleware)

type RouteMetadata

type RouteMetadata struct {
	Method     string
	Path       string
	Handler    string
	Middleware []Middleware
}

RouteMetadata describes a single route in a controller.

func DELETE

func DELETE(path, handler string, middleware ...Middleware) RouteMetadata

func GET

func GET(path, handler string, middleware ...Middleware) RouteMetadata

func OPTIONS

func OPTIONS(path, handler string, middleware ...Middleware) RouteMetadata

func PATCH

func PATCH(path, handler string, middleware ...Middleware) RouteMetadata

func POST

func POST(path, handler string, middleware ...Middleware) RouteMetadata

func PUT

func PUT(path, handler string, middleware ...Middleware) RouteMetadata

type Router

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

Router provides method-based routing and middleware composition.

func NewRouter

func NewRouter() *Router

func (*Router) DELETE

func (r *Router) DELETE(path string, handler HandlerFunc, middleware ...Middleware)

func (*Router) GET

func (r *Router) GET(path string, handler HandlerFunc, middleware ...Middleware)

func (*Router) Group

func (r *Router) Group(prefix string, middleware ...Middleware) *RouteGroup

func (*Router) OPTIONS

func (r *Router) OPTIONS(path string, handler HandlerFunc, middleware ...Middleware)

func (*Router) PATCH

func (r *Router) PATCH(path string, handler HandlerFunc, middleware ...Middleware)

func (*Router) POST

func (r *Router) POST(path string, handler HandlerFunc, middleware ...Middleware)

func (*Router) PUT

func (r *Router) PUT(path string, handler HandlerFunc, middleware ...Middleware)

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

func (*Router) SetValidator

func (r *Router) SetValidator(v Validator)

SetValidator overrides validation engine used by Context.BindJSON for this router.

func (*Router) Use

func (r *Router) Use(middleware ...Middleware)

func (*Router) Validator

func (r *Router) Validator() Validator

Validator returns the validation engine currently attached to this router.

type ServerOptions added in v1.1.0

type ServerOptions struct {
	Addr            string
	ReadTimeout     time.Duration
	WriteTimeout    time.Duration
	IdleTimeout     time.Duration
	ShutdownTimeout time.Duration
}

type ValidationError

type ValidationError struct {
	Field   string
	Rule    string
	Message string
}

type ValidationErrors

type ValidationErrors []ValidationError

func (ValidationErrors) Error

func (ve ValidationErrors) Error() string

func (ValidationErrors) Unwrap

func (ve ValidationErrors) Unwrap() error

type Validator

type Validator interface {
	Validate(any) error
}

Validator is a pluggable validation engine.

func DefaultValidator

func DefaultValidator() Validator

DefaultValidator returns the process-wide default validator.

type ValidatorFunc

type ValidatorFunc func(any) error

ValidatorFunc adapts a function into a Validator.

func (ValidatorFunc) Validate

func (f ValidatorFunc) Validate(v any) error

Jump to

Keyboard shortcuts

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