ghttp

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2026 License: MIT Imports: 38 Imported by: 0

Documentation

Overview

Package ghttp provides the gonex HTTP server, declarative controller registration, middleware composition, request context, and response APIs.

Index

Constants

View Source
const (
	DebugMode   = gin.DebugMode
	ReleaseMode = gin.ReleaseMode
	TestMode    = gin.TestMode
)

Gin mode values supported by the framework.

View Source
const Named = "[GIN-debug]"

Variables

View Source
var ErrGracefulRestartUnsupported = errors.New("graceful restart requires a platform restart manager")
View Source
var ErrRestartHandedOff = errors.New("server restart handoff already completed")
View Source
var ErrRestartInProgress = errors.New("server restart is already in progress")
View Source
var ErrServerNotRunning = errors.New("server is not running")
View Source
var ErrServerRunning = errors.New("server is already running")

Functions

This section is empty.

Types

type CORSOptions

type CORSOptions struct {
	Enabled          bool
	AllowOrigins     []string
	AllowMethods     []string
	AllowHeaders     []string
	ExposeHeaders    []string
	AllowCredentials bool
	MaxAge           int
}

CORSOptions configures cross-origin requests.

type CSRFOptions

type CSRFOptions struct {
	Enabled    bool
	CookieName string
	HeaderName string
	Domain     string
	Secure     bool
	SameSite   http.SameSite
}

CSRFOptions configures double-submit-cookie protection.

type Config

type Config interface {
	Get(key string) any
	GetString(key string) string
	GetInt(key string) int
	GetBool(key string) bool
	Unmarshal(target any) error
}

Config is the configuration contract used by Server.

type Context

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

Context is the framework context over the current Gin request.

func FromContext

func FromContext(ctx context.Context) *Context

FromContext returns the framework context attached to a controller's context.Context. It returns nil when called outside a framework request.

func (*Context) Abort

func (ctx *Context) Abort()

Abort stops the current middleware chain.

func (*Context) ClientIP

func (ctx *Context) ClientIP() string

ClientIP returns the client address resolved by Gin's trusted-proxy policy.

func (*Context) Cookie

func (ctx *Context) Cookie() *CookieManager

func (*Context) File

func (ctx *Context) File(status int, path string)

File serves a local file through net/http.

func (*Context) Get

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

func (*Context) Gin

func (ctx *Context) Gin() *gin.Context

Gin returns the underlying Gin context for integrations that need it.

func (*Context) HTML

func (ctx *Context) HTML(status int, name string, data any) error

HTML renders a named server template into the current response.

func (*Context) Header

func (ctx *Context) Header(name string) string

func (*Context) JSON

func (ctx *Context) JSON(status int, value any)

func (*Context) Logger

func (ctx *Context) Logger() logging.Logger

Logger returns the server logger associated with this request.

func (*Context) Param

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

func (*Context) Query

func (ctx *Context) Query(name string) string

func (*Context) Redirect

func (ctx *Context) Redirect(status int, location string)

Redirect redirects the current request.

func (*Context) Request

func (ctx *Context) Request() *http.Request

func (*Context) RequestID

func (ctx *Context) RequestID() string

RequestID returns the current request correlation ID.

func (*Context) Response

func (ctx *Context) Response() http.ResponseWriter

Response returns the current response writer for integrations that need a standard net/http writer.

func (*Context) Session

func (ctx *Context) Session() (session.Session, error)

Session opens the current request's session.

func (*Context) Set

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

func (*Context) Stream

func (ctx *Context) Stream(status int, contentType string, step func(io.Writer) bool)

Stream writes a streaming response until the callback returns false.

func (*Context) String

func (ctx *Context) String(status int, format string, values ...any)

String writes a plain-text response.

type CookieManager

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

CookieManager provides cookie operations for the current response.

func (*CookieManager) Delete

func (manager *CookieManager) Delete(name string, options CookieOptions) error

func (*CookieManager) Get

func (manager *CookieManager) Get(name string) (string, error)

func (*CookieManager) Set

func (manager *CookieManager) Set(name, value string, options CookieOptions) error

type CookieOptions

type CookieOptions struct {
	Path     string
	Domain   string
	MaxAge   int
	Expires  time.Time
	Secure   bool
	HTTPOnly bool
	SameSite http.SameSite
}

CookieOptions controls a response cookie's security and lifetime flags.

type DefaultResponseEncoder

type DefaultResponseEncoder struct{}

DefaultResponseEncoder writes the framework's default response envelope.

func (DefaultResponseEncoder) Encode

func (DefaultResponseEncoder) Encode(ctx *Context, data any) error

type Error

type Error struct {
	Code       int
	HTTPStatus int
	Message    string
	Cause      error
	Details    any
}

Error is the framework's structured application error.

func NewError

func NewError(code, status int, message string) *Error

NewError constructs a structured application error.

func (*Error) Error

func (err *Error) Error() string

func (*Error) Unwrap

func (err *Error) Unwrap() error

type ErrorHandler

type ErrorHandler func(ctx *Context, err error)

ErrorHandler converts framework, binding, validation, and controller errors into an HTTP response.

type LifecycleHook

type LifecycleHook func(context.Context) error

LifecycleHook is invoked during server startup or shutdown.

type Middleware

type Middleware func(*gin.Context)

Middleware is the application middleware contract.

type OpenAPIOptions

type OpenAPIOptions struct {
	Enabled      bool
	DocumentPath string
	SwaggerPath  string
}

OpenAPIOptions groups the documentation endpoint settings.

type Option

type Option func(*Server)

Option configures a Server during construction.

func WithAddress

func WithAddress(address string) Option

WithAddress sets the TCP address used by Run.

func WithAllowedHosts

func WithAllowedHosts(hosts ...string) Option

WithAllowedHosts limits accepted Host headers.

func WithBindingValidator

func WithBindingValidator(validation *validator.Validate) Option

WithBindingValidator replaces the validator used for binding tags. The supplied validator must already use "binding" as its tag name. It must be a different instance from the validator passed to WithValidator.

func WithCORS

func WithCORS(configuration CORSOptions) Option

WithCORS enables CORS middleware during construction.

func WithCSRF

func WithCSRF(options CSRFOptions) Option

WithCSRF enables double-submit-cookie CSRF protection.

func WithConfig

func WithConfig(configuration Config) Option

WithConfig attaches an application configuration object to the server.

func WithEngine

func WithEngine(engine *gin.Engine) Option

WithEngine supplies a Gin engine. Gonex retains the supplied engine instance but still installs framework middleware and resets Gin's trusted-proxy list to the framework-safe default during initialization. Call SetTrustedProxies on the constructed Server when the application intentionally trusts proxies.

func WithErrorHandler

func WithErrorHandler(handler ErrorHandler) Option

WithErrorHandler replaces the default framework error handler. The built-in OpenAPI error schema describes only Gonex's default error envelope, so a custom handler disables the built-in OpenAPI endpoints by default. A later WithOpenAPI option may explicitly re-enable them when the application owns the resulting documentation contract.

func WithHTTPTimeouts

func WithHTTPTimeouts(read, write, idle time.Duration) Option

WithHTTPTimeouts configures server-side connection timeouts.

func WithHTTPTimeoutsAndShutdown

func WithHTTPTimeoutsAndShutdown(read, write, idle, shutdown time.Duration) Option

func WithLogger

func WithLogger(logger logging.Logger) Option

WithLogger replaces the server logger. Injected loggers remain caller-owned.

func WithMode

func WithMode(mode string) Option

WithMode configures Gin's process-wide mode before Server initialization. The option takes precedence over server.mode in configuration.

func WithName

func WithName(name string) Option

WithName sets the logical name of the server.

func WithOpenAPI

func WithOpenAPI(options OpenAPIOptions) Option

WithOpenAPI configures interface documentation and both endpoint paths.

func WithOpenAPIPath

func WithOpenAPIPath(path string) Option

WithOpenAPIPath changes the generated OpenAPI document endpoint.

func WithRequestID

func WithRequestID(enabled bool) Option

WithRequestID controls automatic request ID generation and propagation. It is enabled by default; disable it for internal high-throughput paths that provide correlation IDs through another mechanism.

func WithRequestLimits

func WithRequestLimits(bodyBytes, multipartMemory int64, headerBytes int) Option

WithRequestLimits configures request body, multipart memory, and header limits. A non-positive value leaves the corresponding default unchanged.

func WithResponseEncoder

func WithResponseEncoder(encoder ResponseEncoder) Option

WithResponseEncoder replaces the default success response encoder. The built-in OpenAPI response schema describes only the default gonex envelope, so supplying a custom encoder disables the built-in OpenAPI endpoints by default. A later WithOpenAPI option may explicitly re-enable them when the application intentionally accepts or replaces that documentation contract.

func WithRestartManager

func WithRestartManager(manager RestartManager) Option

WithRestartManager supplies a platform-specific restart implementation.

func WithScheduler

func WithScheduler(manager scheduler.Scheduler) Option

WithScheduler supplies a scheduler whose lifecycle is managed exclusively by the configured Server. The caller must not inject the same instance into multiple Servers.

func WithSchedulerOptions

func WithSchedulerOptions(options SchedulerOptions) Option

WithSchedulerOptions configures the Server-owned default scheduler. An explicitly supplied scheduler through WithScheduler retains its own engine configuration and lifecycle ownership remains with Server.

func WithSecurityOptions

func WithSecurityOptions(options SecurityOptions) Option

WithSecurityOptions configures host, CORS, and CSRF policy together.

func WithSessionCookieOptions

func WithSessionCookieOptions(options CookieOptions) Option

WithSessionCookieOptions configures the session identifier cookie flags.

func WithSessionManager

func WithSessionManager(manager *SessionManager) Option

WithSessionManager attaches a session manager to the server.

func WithSessionOptions

func WithSessionOptions(options SessionOptions) Option

WithSessionOptions configures session ownership and cookie flags together.

func WithShutdownTimeout

func WithShutdownTimeout(timeout time.Duration) Option

WithShutdownTimeout configures the maximum graceful shutdown duration.

func WithSwaggerPath

func WithSwaggerPath(path string) Option

WithSwaggerPath changes the embedded API explorer endpoint.

func WithTLS

func WithTLS(certFile, keyFile string) Option

WithTLS enables TLS when Run is used.

func WithTLSOptions

func WithTLSOptions(options TLSOptions) Option

WithTLSOptions configures TLS as one subsystem option.

func WithTemplateRoot

func WithTemplateRoot(root string) Option

WithTemplateRoot loads templates during server construction.

func WithTimeouts

func WithTimeouts(options TimeoutOptions) Option

WithTimeouts configures all supplied server timeouts as one subsystem option. Non-positive values leave the corresponding default unchanged.

func WithValidator

func WithValidator(validation *validator.Validate) Option

WithValidator replaces the validator used for validate tags and custom struct-level rules. The caller must finish configuring validation before constructing the Server and must not mutate it afterward.

type Response

type Response struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    any    `json:"data,omitempty"`
	Details any    `json:"details,omitempty"`
}

Response is the default success envelope used by the framework.

type ResponseEncoder

type ResponseEncoder interface {
	Encode(ctx *Context, data any) error
}

ResponseEncoder converts successful controller data into an HTTP response.

type RestartManager

type RestartManager interface {
	Restart(ctx context.Context) error
}

RestartManager is the platform boundary for zero-downtime process restart. Implementations may coordinate listener FD inheritance and readiness with a supervisor without coupling those concerns to the Server core.

type Route

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

Route is a pre-registration route scope used to attach middleware to one method/path pair without exposing Gin's route registry as the source of truth. Configure it before Bind.

func (*Route) Use

func (route *Route) Use(middleware ...Middleware) error

Use attaches middleware to this route before its Controller is bound.

type RouterGroup

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

RouterGroup scopes route paths and middleware without exposing Gin as the route registry's source of truth.

func (*RouterGroup) Bind

func (group *RouterGroup) Bind(controllers ...any) error

Bind scans and registers controllers under the group's path prefix.

func (*RouterGroup) Middleware

func (group *RouterGroup) Middleware(middleware ...Middleware) *RouterGroup

Middleware adds middleware to this group.

func (*RouterGroup) String

func (group *RouterGroup) String() string

type SchedulerOptions

type SchedulerOptions struct {
	Enabled  bool
	Location *time.Location
}

SchedulerOptions controls the built-in Server scheduler. A nil Location uses time.Local for cron expressions without an explicit timezone prefix.

type SecurityOptions

type SecurityOptions struct {
	AllowedHosts []string
	CORS         CORSOptions
	CSRF         CSRFOptions
}

SecurityOptions groups host, CORS, and CSRF settings.

type Server

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

Server is the framework's HTTP server and route owner.

func NewServer

func NewServer(options ...Option) *Server

NewServer creates an independent Server instance.

func (*Server) AddTemplateFunc

func (server *Server) AddTemplateFunc(name string, function any) error

AddTemplateFunc registers a function available to templates.

func (*Server) Address

func (server *Server) Address() string

Address returns the configured listening address.

func (*Server) Bind

func (server *Server) Bind(controller any, middleware ...Middleware) error

Bind scans a controller, creates route definitions, and registers those definitions with both the framework registry and Gin.

func (*Server) Close

func (server *Server) Close() error

Close performs a bounded graceful shutdown.

func (*Server) Config

func (server *Server) Config() Config

Config returns the attached application configuration.

func (*Server) EnableCORS

func (server *Server) EnableCORS(options CORSOptions) error

func (*Server) EnableCSRF

func (server *Server) EnableCSRF(options CSRFOptions) error

EnableCSRF enables double-submit-cookie CSRF protection for unsafe methods.

func (*Server) EnableOpenAPI

func (server *Server) EnableOpenAPI(enabled bool)

EnableOpenAPI enables or disables the interface documentation feature, including both the generated OpenAPI JSON and Swagger UI endpoints.

func (*Server) Engine

func (server *Server) Engine() *gin.Engine

Engine exposes the underlying Gin engine for controlled integrations. Mutate it only during application initialization, before Run, RunContext, or Listen. Routes registered directly on Gin are intentionally outside Gonex's registry and OpenAPI contract.

func (*Server) Err

func (server *Server) Err() error

Err returns a construction or configuration error that prevents the server from starting safely.

func (*Server) Go

func (server *Server) Go(task func(context.Context))

Go tracks a background task for graceful shutdown.

func (*Server) Group

func (server *Server) Group(prefix string, handler func(*RouterGroup))

Group creates a path and middleware scope and invokes handler with it.

func (*Server) HTTPServer

func (server *Server) HTTPServer() *http.Server

HTTPServer returns the underlying net/http server for advanced integrations. Mutate it only during application initialization, before the Server starts; runtime changes bypass Gonex's lifecycle and synchronization guarantees.

func (*Server) IsDebug

func (server *Server) IsDebug() bool

IsDebug reports whether this Server runs in debug mode.

The value belongs to the Server instance and does not read Gin's global mode, so components can make decisions for the correct server when more than one server is used in a process.

func (*Server) Listen

func (server *Server) Listen(address string) error

Listen starts the configured HTTP server on address.

func (*Server) ListenTLS

func (server *Server) ListenTLS(address, certFile, keyFile string) error

ListenTLS starts the configured HTTPS server on address.

func (*Server) Logger

func (server *Server) Logger() logging.Logger

Logger returns the server's framework logger.

func (*Server) Mode

func (server *Server) Mode() string

Mode returns the Gin mode used by this Server.

func (*Server) MustBind

func (server *Server) MustBind(controller any)

MustBind is the startup-oriented variant of Bind. It panics when a controller does not satisfy the declared route contract.

func (*Server) Name

func (server *Server) Name() string

Name returns the server's logical name.

func (*Server) OnShutdown

func (server *Server) OnShutdown(hook LifecycleHook)

OnShutdown registers a hook before active requests are drained.

func (*Server) OnStart

func (server *Server) OnStart(hook LifecycleHook)

OnStart registers a hook before the listener starts accepting requests.

func (*Server) OnStarted

func (server *Server) OnStarted(hook LifecycleHook)

OnStarted registers a hook after the HTTP server has entered its accept loop.

func (*Server) OnStop

func (server *Server) OnStop(hook LifecycleHook)

OnStop registers a hook after the listener and tracked tasks stop.

func (*Server) OpenAPI

func (server *Server) OpenAPI() openapi.Document

OpenAPI builds a cached document from the framework route registry.

func (*Server) OpenAPIJSON

func (server *Server) OpenAPIJSON() ([]byte, error)

OpenAPIJSON returns the generated document as indented JSON.

func (*Server) PrintRoutes

func (server *Server) PrintRoutes(writer io.Writer) error

PrintRoutes writes the framework route table to writer.

func (*Server) Restart

func (server *Server) Restart(ctx context.Context) error

Restart delegates to the configured restart manager.

func (*Server) RestartManager

func (server *Server) RestartManager() RestartManager

RestartManager returns the configured restart implementation.

func (*Server) Route

func (server *Server) Route(method, path string) *Route

Route returns a route-specific middleware scope. The path is the final registered path, including a Group prefix when applicable.

func (*Server) RouteTable

func (server *Server) RouteTable() string

RouteTable returns a stable, human-readable route table for diagnostics.

func (*Server) Routes

func (server *Server) Routes() []router.RouteMetadata

Routes returns a snapshot of the framework-owned route table.

func (*Server) Run

func (server *Server) Run(address ...string) error

Run starts the HTTP server and blocks until it stops. An optional address override is claimed atomically with the running state.

func (*Server) RunContext

func (server *Server) RunContext(ctx context.Context) error

RunContext runs the server until the supplied context is canceled or the HTTP server returns an error.

func (*Server) RunTLS

func (server *Server) RunTLS(certFile, keyFile string) error

RunTLS starts the server with a certificate and private key.

func (*Server) Scheduler

func (server *Server) Scheduler() scheduler.Scheduler

Scheduler returns the Server-owned scheduler. It starts before the HTTP listener and stops during graceful shutdown; each Server has an independent scheduler instance unless an application intentionally supplies one.

func (*Server) ServeHTTP

func (server *Server) ServeHTTP(writer http.ResponseWriter, request *http.Request)

ServeHTTP makes Server usable with httptest and net/http adapters.

func (*Server) SessionManager

func (server *Server) SessionManager() *SessionManager

SessionManager returns the configured session manager.

func (*Server) SetAllowedHosts

func (server *Server) SetAllowedHosts(hosts ...string)

SetAllowedHosts limits Host headers accepted by the HTTP server. An empty list disables host validation. Entries may be exact hosts or *.example.com.

func (*Server) SetTemplateRoot

func (server *Server) SetTemplateRoot(root string) error

SetTemplateRoot configures and loads the server template directory. The Server option is published only after the template manager accepts the root.

func (*Server) SetTrustedProxies

func (server *Server) SetTrustedProxies(proxies []string) error

SetTrustedProxies configures which proxies Gin may trust for client IP resolution. Passing nil disables proxy trust. Proxy configuration is serialized with route registration and startup because it mutates Gin.

func (*Server) Shutdown

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

Shutdown gracefully stops the HTTP server. Lifecycle hooks keep their re-entry protection; once those hooks finish, concurrent callers coalesce on one resource-cleanup attempt so HTTP, templates, scheduler, tasks, and logger are not closed concurrently.

func (*Server) Static

func (server *Server) Static(relative, root string) error

func (*Server) StaticFS

func (server *Server) StaticFS(relative string, filesystem fs.FS) error

func (*Server) StaticFSWithOptions

func (server *Server) StaticFSWithOptions(relative string, filesystem fs.FS, options StaticOptions) error

func (*Server) StaticFile

func (server *Server) StaticFile(relative, path string) error

func (*Server) StaticFileWithOptions

func (server *Server) StaticFileWithOptions(relative, path string, options StaticOptions) error

func (*Server) StaticWithOptions

func (server *Server) StaticWithOptions(relative, root string, options StaticOptions) error

func (*Server) Templates

func (server *Server) Templates() *template.Manager

Templates returns the server template manager.

func (*Server) Use

func (server *Server) Use(middleware ...Middleware) error

Use adds application middleware to all routes registered on the server.

type SessionManager

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

SessionManager owns session cookies and delegates persistence to a storage backend.

func NewSessionManager

func NewSessionManager(storage session.Storage, cookieName string, ttl time.Duration) *SessionManager

NewSessionManager creates an HTTP session manager over storage. Storage I/O receives each request context; the application retains ownership of storage and any external client it uses. Nil and typed-nil storage both select the process-local memory backend.

func (*SessionManager) CookieOptions

func (manager *SessionManager) CookieOptions() CookieOptions

CookieOptions returns a copy of the session identifier cookie options.

func (*SessionManager) Open

func (manager *SessionManager) Open(ctx *Context) (session.Session, error)

func (*SessionManager) SetCookieOptions

func (manager *SessionManager) SetCookieOptions(options CookieOptions)

SetCookieOptions replaces the flags used for the session identifier cookie. SameSite=None always implies Secure so runtime mutation cannot weaken the framework's session-cookie invariant.

type SessionOptions

type SessionOptions struct {
	Manager       *SessionManager
	CookieOptions *CookieOptions
}

SessionOptions groups session manager and cookie settings.

type StaticOptions

type StaticOptions struct {
	CacheControl string
	Index        string
	SPAFallback  bool
	Extensions   []string
}

StaticOptions controls cache headers, index serving, SPA fallback, and the file extensions a mount may serve. A nil Extensions slice uses the safe defaults; an empty non-nil slice denies all files.

type TLSOptions

type TLSOptions struct {
	Enabled  bool
	CertFile string
	KeyFile  string
}

TLSOptions groups the TLS settings controlled by construction options.

type TimeoutOptions

type TimeoutOptions struct {
	Read, Write, Idle, Shutdown time.Duration
}

TimeoutOptions groups the HTTP and graceful-shutdown timeouts.

type ValidationFieldError

type ValidationFieldError struct {
	Field string `json:"field"`
	Tag   string `json:"tag"`
	Param string `json:"param,omitempty"`
}

func (ValidationFieldError) String

func (fieldError ValidationFieldError) String() string

Directories

Path Synopsis
internal
ginruntime
Package ginruntime contains the only ghttp-owned adapter for Gin's process-wide configuration.
Package ginruntime contains the only ghttp-owned adapter for Gin's process-wide configuration.

Jump to

Keyboard shortcuts

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