Documentation
¶
Overview ¶
Package ghttp provides the gonex HTTP server, declarative controller registration, middleware composition, request context, and response APIs.
Index ¶
- Constants
- Variables
- type CORSOptions
- type CSRFOptions
- type Config
- type Context
- func (ctx *Context) Abort()
- func (ctx *Context) ClientIP() string
- func (ctx *Context) Cookie() *CookieManager
- func (ctx *Context) File(status int, path string)
- func (ctx *Context) Get(key string) (any, bool)
- func (ctx *Context) Gin() *gin.Context
- func (ctx *Context) HTML(status int, name string, data any) error
- func (ctx *Context) Header(name string) string
- func (ctx *Context) JSON(status int, value any)
- func (ctx *Context) Logger() logging.Logger
- func (ctx *Context) Param(name string) string
- func (ctx *Context) Query(name string) string
- func (ctx *Context) Redirect(status int, location string)
- func (ctx *Context) Request() *http.Request
- func (ctx *Context) RequestID() string
- func (ctx *Context) Response() http.ResponseWriter
- func (ctx *Context) Session() (session.Session, error)
- func (ctx *Context) Set(key string, value any)
- func (ctx *Context) Stream(status int, contentType string, step func(io.Writer) bool)
- func (ctx *Context) String(status int, format string, values ...any)
- type CookieManager
- type CookieOptions
- type DefaultResponseEncoder
- type Error
- type ErrorHandler
- type LifecycleHook
- type Middleware
- type OpenAPIOptions
- type Option
- func WithAddress(address string) Option
- func WithAllowedHosts(hosts ...string) Option
- func WithBindingValidator(validation *validator.Validate) Option
- func WithCORS(configuration CORSOptions) Option
- func WithCSRF(options CSRFOptions) Option
- func WithConfig(configuration Config) Option
- func WithEngine(engine *gin.Engine) Option
- func WithErrorHandler(handler ErrorHandler) Option
- func WithHTTPTimeouts(read, write, idle time.Duration) Option
- func WithHTTPTimeoutsAndShutdown(read, write, idle, shutdown time.Duration) Option
- func WithLogger(logger logging.Logger) Option
- func WithMode(mode string) Option
- func WithName(name string) Option
- func WithOpenAPI(options OpenAPIOptions) Option
- func WithOpenAPIPath(path string) Option
- func WithRequestID(enabled bool) Option
- func WithRequestLimits(bodyBytes, multipartMemory int64, headerBytes int) Option
- func WithResponseEncoder(encoder ResponseEncoder) Option
- func WithRestartManager(manager RestartManager) Option
- func WithScheduler(manager scheduler.Scheduler) Option
- func WithSchedulerOptions(options SchedulerOptions) Option
- func WithSecurityOptions(options SecurityOptions) Option
- func WithSessionCookieOptions(options CookieOptions) Option
- func WithSessionManager(manager *SessionManager) Option
- func WithSessionOptions(options SessionOptions) Option
- func WithShutdownTimeout(timeout time.Duration) Option
- func WithSwaggerPath(path string) Option
- func WithTLS(certFile, keyFile string) Option
- func WithTLSOptions(options TLSOptions) Option
- func WithTemplateRoot(root string) Option
- func WithTimeouts(options TimeoutOptions) Option
- func WithValidator(validation *validator.Validate) Option
- type Response
- type ResponseEncoder
- type RestartManager
- type Route
- type RouterGroup
- type SchedulerOptions
- type SecurityOptions
- type Server
- func (server *Server) AddTemplateFunc(name string, function any) error
- func (server *Server) Address() string
- func (server *Server) Bind(controller any, middleware ...Middleware) error
- func (server *Server) Close() error
- func (server *Server) Config() Config
- func (server *Server) EnableCORS(options CORSOptions) error
- func (server *Server) EnableCSRF(options CSRFOptions) error
- func (server *Server) EnableOpenAPI(enabled bool)
- func (server *Server) Engine() *gin.Engine
- func (server *Server) Err() error
- func (server *Server) Go(task func(context.Context))
- func (server *Server) Group(prefix string, handler func(*RouterGroup))
- func (server *Server) HTTPServer() *http.Server
- func (server *Server) IsDebug() bool
- func (server *Server) Listen(address string) error
- func (server *Server) ListenTLS(address, certFile, keyFile string) error
- func (server *Server) Logger() logging.Logger
- func (server *Server) Mode() string
- func (server *Server) MustBind(controller any)
- func (server *Server) Name() string
- func (server *Server) OnShutdown(hook LifecycleHook)
- func (server *Server) OnStart(hook LifecycleHook)
- func (server *Server) OnStarted(hook LifecycleHook)
- func (server *Server) OnStop(hook LifecycleHook)
- func (server *Server) OpenAPI() openapi.Document
- func (server *Server) OpenAPIJSON() ([]byte, error)
- func (server *Server) PrintRoutes(writer io.Writer) error
- func (server *Server) Restart(ctx context.Context) error
- func (server *Server) RestartManager() RestartManager
- func (server *Server) Route(method, path string) *Route
- func (server *Server) RouteTable() string
- func (server *Server) Routes() []router.RouteMetadata
- func (server *Server) Run(address ...string) error
- func (server *Server) RunContext(ctx context.Context) error
- func (server *Server) RunTLS(certFile, keyFile string) error
- func (server *Server) Scheduler() scheduler.Scheduler
- func (server *Server) ServeHTTP(writer http.ResponseWriter, request *http.Request)
- func (server *Server) SessionManager() *SessionManager
- func (server *Server) SetAllowedHosts(hosts ...string)
- func (server *Server) SetTemplateRoot(root string) error
- func (server *Server) SetTrustedProxies(proxies []string) error
- func (server *Server) Shutdown(ctx context.Context) error
- func (server *Server) Static(relative, root string) error
- func (server *Server) StaticFS(relative string, filesystem fs.FS) error
- func (server *Server) StaticFSWithOptions(relative string, filesystem fs.FS, options StaticOptions) error
- func (server *Server) StaticFile(relative, path string) error
- func (server *Server) StaticFileWithOptions(relative, path string, options StaticOptions) error
- func (server *Server) StaticWithOptions(relative, root string, options StaticOptions) error
- func (server *Server) Templates() *template.Manager
- func (server *Server) Use(middleware ...Middleware) error
- type SessionManager
- type SessionOptions
- type StaticOptions
- type TLSOptions
- type TimeoutOptions
- type ValidationFieldError
Constants ¶
const ( DebugMode = gin.DebugMode ReleaseMode = gin.ReleaseMode TestMode = gin.TestMode )
Gin mode values supported by the framework.
const Named = "[GIN-debug]"
Variables ¶
var ErrGracefulRestartUnsupported = errors.New("graceful restart requires a platform restart manager")
var ErrRestartHandedOff = errors.New("server restart handoff already completed")
var ErrRestartInProgress = errors.New("server restart is already in progress")
var ErrServerNotRunning = errors.New("server is not running")
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 ¶
FromContext returns the framework context attached to a controller's context.Context. It returns nil when called outside a framework request.
func (*Context) ClientIP ¶
ClientIP returns the client address resolved by Gin's trusted-proxy policy.
func (*Context) Cookie ¶
func (ctx *Context) Cookie() *CookieManager
func (*Context) Response ¶
func (ctx *Context) Response() http.ResponseWriter
Response returns the current response writer for integrations that need a standard net/http writer.
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) 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.
type Error ¶
Error is the framework's structured application error.
type ErrorHandler ¶
ErrorHandler converts framework, binding, validation, and controller errors into an HTTP response.
type LifecycleHook ¶
LifecycleHook is invoked during server startup or shutdown.
type Middleware ¶
Middleware is the application middleware contract.
type OpenAPIOptions ¶
OpenAPIOptions groups the documentation endpoint settings.
type Option ¶
type Option func(*Server)
Option configures a Server during construction.
func WithAddress ¶
WithAddress sets the TCP address used by Run.
func WithAllowedHosts ¶
WithAllowedHosts limits accepted Host headers.
func WithBindingValidator ¶
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 ¶
WithConfig attaches an application configuration object to the server.
func WithEngine ¶
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 ¶
WithHTTPTimeouts configures server-side connection timeouts.
func WithLogger ¶
WithLogger replaces the server logger. Injected loggers remain caller-owned.
func WithMode ¶
WithMode configures Gin's process-wide mode before Server initialization. The option takes precedence over server.mode in configuration.
func WithOpenAPI ¶
func WithOpenAPI(options OpenAPIOptions) Option
WithOpenAPI configures interface documentation and both endpoint paths.
func WithOpenAPIPath ¶
WithOpenAPIPath changes the generated OpenAPI document endpoint.
func WithRequestID ¶
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 ¶
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 ¶
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 ¶
WithShutdownTimeout configures the maximum graceful shutdown duration.
func WithSwaggerPath ¶
WithSwaggerPath changes the embedded API explorer endpoint.
func WithTLSOptions ¶
func WithTLSOptions(options TLSOptions) Option
WithTLSOptions configures TLS as one subsystem option.
func WithTemplateRoot ¶
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 ¶
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 ¶
ResponseEncoder converts successful controller data into an HTTP response.
type RestartManager ¶
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 ¶
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 (*Server) AddTemplateFunc ¶
AddTemplateFunc registers a function available to templates.
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) 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 ¶
EnableOpenAPI enables or disables the interface documentation feature, including both the generated OpenAPI JSON and Swagger UI endpoints.
func (*Server) 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 ¶
Err returns a construction or configuration error that prevents the server from starting safely.
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 ¶
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 ¶
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) MustBind ¶
MustBind is the startup-oriented variant of Bind. It panics when a controller does not satisfy the declared route contract.
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) OpenAPIJSON ¶
OpenAPIJSON returns the generated document as indented JSON.
func (*Server) PrintRoutes ¶
PrintRoutes writes the framework route table to writer.
func (*Server) RestartManager ¶
func (server *Server) RestartManager() RestartManager
RestartManager returns the configured restart implementation.
func (*Server) Route ¶
Route returns a route-specific middleware scope. The path is the final registered path, including a Group prefix when applicable.
func (*Server) RouteTable ¶
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 ¶
Run starts the HTTP server and blocks until it stops. An optional address override is claimed atomically with the running state.
func (*Server) RunContext ¶
RunContext runs the server until the supplied context is canceled or the HTTP server returns an error.
func (*Server) 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 ¶
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 ¶
SetTemplateRoot configures and loads the server template directory. The Server option is published only after the template manager accepts the root.
func (*Server) SetTrustedProxies ¶
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 ¶
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) StaticFSWithOptions ¶
func (*Server) StaticFile ¶
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) 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 ¶
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 ¶
TLSOptions groups the TLS settings controlled by construction options.
type TimeoutOptions ¶
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
Source Files
¶
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. |