Documentation
¶
Index ¶
- Constants
- Variables
- func ContextServiceOf[T any](c *Context) (service T, ok bool)
- func GetVersion() string
- func GetVersionHeader() string
- func ServiceOf[T any](a *App) (service T, ok bool)
- type App
- func (a *App) Connect(path string, handlers ...RouteHandler) error
- func (a *App) ConnectDB(driverName, dataSourceName string) error
- func (a *App) Cron(id string, schedule string, handler interface{}) error
- func (a *App) Delete(path string, handlers ...RouteHandler) error
- func (a *App) Get(path string, handlers ...RouteHandler) error
- func (a *App) GetDB() *sql.DB
- func (a *App) GetService(serviceType reflect.Type) interface{}
- func (a *App) Group(prefix string) *Group
- func (a *App) Head(path string, handlers ...RouteHandler) error
- func (a *App) Injectable(service interface{})
- func (a *App) Options(path string, handlers ...RouteHandler) error
- func (a *App) Patch(path string, handlers ...RouteHandler) error
- func (a *App) Post(path string, handlers ...RouteHandler) error
- func (a *App) Put(path string, handlers ...RouteHandler) error
- func (a *App) RemoveCRON(id string)
- func (a *App) Serve(port ...string) error
- func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (a *App) SetConfig(config *Config)
- func (a *App) SetFileUpload(upload *FileUpload)
- func (a *App) SetTemplateEngine(engine *TemplateEngine)
- func (a *App) SetWebSocketHandler(handler *WebSocketHandler)
- func (a *App) StartCRON()
- func (a *App) StopCRON()
- func (a *App) Trace(path string, handlers ...RouteHandler) error
- func (a *App) Use(middleware ...Middleware)
- func (a *App) Validate(s any) ValidationErrors
- func (a *App) Version() string
- type BindOptions
- type Config
- type Context
- func (c *Context) Bind(v interface{}, opts ...*BindOptions) error
- func (c *Context) BindForm(v interface{}, opts ...*BindOptions) error
- func (c *Context) BindJSON(v interface{}, opts ...*BindOptions) error
- func (c *Context) BindQuery(v interface{}, opts ...*BindOptions) error
- func (c *Context) BindXML(v interface{}, opts ...*BindOptions) error
- func (c *Context) Body() (string, error)
- func (c *Context) BodyParser(out interface{}) error
- func (c *Context) BroadcastToRoom(roomID string, message []byte) error
- func (c *Context) DB() *sql.DB
- func (c *Context) File(name string) (*multipart.FileHeader, error)
- func (c *Context) Files(name string) ([]*multipart.FileHeader, error)
- func (c *Context) FormFile(name string) (*multipart.FileHeader, error)
- func (c *Context) FormFiles(name string) ([]*multipart.FileHeader, error)
- func (c *Context) Get(key string) interface{}
- func (c *Context) HTML(data string) error
- func (c *Context) HasQuery(name string) bool
- func (c *Context) IP() string
- func (c *Context) JSON(data interface{}) error
- func (c *Context) JoinRoom(roomID string, conn *websocket.Conn)
- func (c *Context) LeaveRoom(roomID string, conn *websocket.Conn)
- func (c *Context) Next() error
- func (c *Context) Param(name string) string
- func (c *Context) Query(name string) string
- func (c *Context) RemoteIP() string
- func (c *Context) Render(name string, data interface{}) error
- func (c *Context) SaveFile(fileHeader *multipart.FileHeader, dst string) error
- func (c *Context) Send(data any) error
- func (c *Context) Service(name interface{}) interface{}
- func (c *Context) Set(key string, value interface{})
- func (c *Context) Static(filepath string) error
- func (c *Context) Status(code int) *Context
- func (c *Context) String(data string) error
- func (c *Context) Upgrade() (*websocket.Conn, error)
- func (c *Context) Version() string
- type CronJob
- type CronScheduler
- type DBRoutedHandler
- type FileUpload
- type Group
- func (g *Group) Add(method, path string, handlers ...RouteHandler) error
- func (g *Group) Connect(path string, handlers ...RouteHandler) error
- func (g *Group) Delete(path string, handlers ...RouteHandler) error
- func (g *Group) Get(path string, handlers ...RouteHandler) error
- func (g *Group) Group(prefix string) *Group
- func (g *Group) Head(path string, handlers ...RouteHandler) error
- func (g *Group) Options(path string, handlers ...RouteHandler) error
- func (g *Group) Patch(path string, handlers ...RouteHandler) error
- func (g *Group) Post(path string, handlers ...RouteHandler) error
- func (g *Group) Put(path string, handlers ...RouteHandler) error
- func (g *Group) Trace(path string, handlers ...RouteHandler) error
- func (g *Group) Use(middleware ...Middleware) *Group
- type HTTPError
- type Map
- type Middleware
- type Room
- type Route
- type RouteCache
- type RouteHandler
- type RouteHandlerMap
- type RouteMap
- type RouteNode
- type Router
- type TemplateEngine
- func (e *TemplateEngine) AddFunc(name string, fn interface{})
- func (e *TemplateEngine) ClearCache()
- func (e *TemplateEngine) DisableCache()
- func (e *TemplateEngine) GetDirectory() string
- func (e *TemplateEngine) LoadTemplates() error
- func (e *TemplateEngine) Render(w io.Writer, name string, data interface{}) error
- func (e *TemplateEngine) SetExtension(ext string)
- func (e *TemplateEngine) SetFuncMap(funcMap template.FuncMap)
- type ValidationError
- type ValidationErrors
- type Validator
- type WebSocketHandler
Constants ¶
const ( ParamIdentifier = ':' WildcardIdentifier = '*' )
const ( HeaderAuthorization = "Authorization" HeaderProxyAuthenticate = "Proxy-Authenticate" HeaderProxyAuthorization = "Proxy-Authorization" HeaderWWWAuthenticate = "WWW-Authenticate" HeaderAge = "Age" HeaderCacheControl = "Cache-Control" HeaderClearSiteData = "Clear-Site-Data" HeaderExpires = "Expires" HeaderPragma = "Pragma" HeaderWarning = "Warning" HeaderAcceptCH = "Accept-CH" HeaderAcceptCHLifetime = "Accept-CH-Lifetime" HeaderContentDPR = "Content-DPR" HeaderDPR = "DPR" HeaderEarlyData = "Early-Data" HeaderSaveData = "Save-Data" HeaderViewportWidth = "Viewport-Width" HeaderWidth = "Width" HeaderETag = "ETag" HeaderIfMatch = "If-Match" HeaderIfModifiedSince = "If-Modified-Since" HeaderIfNoneMatch = "If-None-Match" HeaderIfUnmodifiedSince = "If-Unmodified-Since" HeaderLastModified = "Last-Modified" HeaderVary = "Vary" HeaderConnection = "Connection" HeaderKeepAlive = "Keep-Alive" HeaderAccept = "Accept" HeaderAcceptCharset = "Accept-Charset" HeaderAcceptEncoding = "Accept-Encoding" HeaderAcceptLanguage = "Accept-Language" HeaderCookie = "Cookie" HeaderExpect = "Expect" HeaderMaxForwards = "Max-Forwards" HeaderSetCookie = "Set-Cookie" HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials" HeaderAccessControlAllowHeaders = "Access-Control-Allow-Headers" HeaderAccessControlAllowMethods = "Access-Control-Allow-Methods" HeaderAccessControlAllowOrigin = "Access-Control-Allow-Origin" HeaderAccessControlExposeHeaders = "Access-Control-Expose-Headers" HeaderAccessControlMaxAge = "Access-Control-Max-Age" HeaderAccessControlRequestHeaders = "Access-Control-Request-Headers" HeaderAccessControlRequestMethod = "Access-Control-Request-Method" HeaderOrigin = "Origin" HeaderTimingAllowOrigin = "Timing-Allow-Origin" HeaderXPermittedCrossDomainPolicies = "X-Permitted-Cross-Domain-Policies" HeaderDNT = "DNT" HeaderTk = "Tk" HeaderContentDisposition = "Content-Disposition" HeaderContentEncoding = "Content-Encoding" HeaderContentLanguage = "Content-Language" HeaderContentLength = "Content-Length" HeaderContentLocation = "Content-Location" HeaderContentType = "Content-Type" HeaderForwarded = "Forwarded" HeaderVia = "Via" HeaderXForwardedFor = "X-Forwarded-For" HeaderXForwardedHost = "X-Forwarded-Host" HeaderXForwardedProto = "X-Forwarded-Proto" HeaderXForwardedProtocol = "X-Forwarded-Protocol" HeaderXForwardedSsl = "X-Forwarded-Ssl" HeaderXUrlScheme = "X-Url-Scheme" HeaderLocation = "Location" HeaderFrom = "From" HeaderHost = "Host" HeaderReferer = "Referer" HeaderReferrerPolicy = "Referrer-Policy" HeaderUserAgent = "User-Agent" HeaderAllow = "Allow" HeaderServer = "Server" HeaderAcceptRanges = "Accept-Ranges" HeaderContentRange = "Content-Range" HeaderIfRange = "If-Range" HeaderRange = "Range" HeaderContentSecurityPolicy = "Content-Security-Policy" HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only" HeaderCrossOriginResourcePolicy = "Cross-Origin-Resource-Policy" HeaderExpectCT = "Expect-CT" HeaderFeaturePolicy = "Feature-Policy" HeaderPublicKeyPins = "Public-Key-Pins" HeaderPublicKeyPinsReportOnly = "Public-Key-Pins-Report-Only" HeaderStrictTransportSecurity = "Strict-Transport-Security" HeaderUpgradeInsecureRequests = "Upgrade-Insecure-Requests" HeaderXContentTypeOptions = "X-Content-Type-Options" HeaderXDownloadOptions = "X-Download-Options" HeaderXFrameOptions = "X-Frame-Options" HeaderXPoweredBy = "X-Powered-By" HeaderXXSSProtection = "X-XSS-Protection" HeaderLastEventID = "Last-Event-ID" HeaderNEL = "NEL" HeaderPingFrom = "Ping-From" HeaderPingTo = "Ping-To" HeaderReportTo = "Report-To" HeaderTE = "TE" HeaderTrailer = "Trailer" HeaderTransferEncoding = "Transfer-Encoding" HeaderSecWebSocketAccept = "Sec-WebSocket-Accept" HeaderSecWebSocketExtensions = "Sec-WebSocket-Extensions" HeaderSecWebSocketKey = "Sec-WebSocket-Key" HeaderSecWebSocketProtocol = "Sec-WebSocket-Protocol" HeaderSecWebSocketVersion = "Sec-WebSocket-Version" HeaderAcceptPatch = "Accept-Patch" HeaderAcceptPushPolicy = "Accept-Push-Policy" HeaderAcceptSignature = "Accept-Signature" HeaderAltSvc = "Alt-Svc" HeaderDate = "Date" HeaderIndex = "Index" HeaderLargeAllocation = "Large-Allocation" HeaderLink = "Link" HeaderPushPolicy = "Push-Policy" HeaderRetryAfter = "Retry-After" HeaderServerTiming = "Server-Timing" HeaderSignature = "Signature" HeaderSignedHeaders = "Signed-Headers" HeaderSourceMap = "SourceMap" HeaderUpgrade = "Upgrade" HeaderXDNSPrefetchControl = "X-DNS-Prefetch-Control" HeaderXPingback = "X-Pingback" HeaderXRequestID = "X-Request-ID" HeaderXRequestedWith = "X-Requested-With" HeaderXRobotsTag = "X-Robots-Tag" HeaderXUACompatible = "X-UA-Compatible" )
const ( MethodGet = "GET" // RFC 7231, 4.3.1 MethodHead = "HEAD" // RFC 7231, 4.3.2 MethodPost = "POST" // RFC 7231, 4.3.3 MethodPut = "PUT" // RFC 7231, 4.3.4 MethodPatch = "PATCH" // RFC 5789 MethodDelete = "DELETE" // RFC 7231, 4.3.5 MethodConnect = "CONNECT" // RFC 7231, 4.3.6 MethodOptions = "OPTIONS" // RFC 7231, 4.3.7 MethodTrace = "TRACE" // RFC 7231, 4.3.8 )
HTTP methods
const ( StatusContinue = 100 // RFC 7231, 6.2.1 StatusSwitchingProtocols = 101 // RFC 7231, 6.2.2 StatusProcessing = 102 // RFC 2518, 10.1 StatusEarlyHints = 103 // RFC 8297 StatusOK = 200 // RFC 7231, 6.3.1 StatusCreated = 201 // RFC 7231, 6.3.2 StatusAccepted = 202 // RFC 7231, 6.3.3 StatusNonAuthoritativeInformation = 203 // RFC 7231, 6.3.4 StatusNoContent = 204 // RFC 7231, 6.3.5 StatusResetContent = 205 // RFC 7231, 6.3.6 StatusPartialContent = 206 // RFC 7233, 4.1 StatusMultiStatus = 207 // RFC 4918, 11.1 StatusAlreadyReported = 208 // RFC 5842, 7.1 StatusIMUsed = 226 // RFC 3229, 10.4.1 StatusMultipleChoices = 300 // RFC 7231, 6.4.1 StatusMovedPermanently = 301 // RFC 7231, 6.4.2 StatusFound = 302 // RFC 7231, 6.4.3 StatusSeeOther = 303 // RFC 7231, 6.4.4 StatusNotModified = 304 // RFC 7232, 4.1 StatusUseProxy = 305 // RFC 7231, 6.4.5 StatusTemporaryRedirect = 307 // RFC 7231, 6.4.7 StatusPermanentRedirect = 308 // RFC 7538, 3 StatusBadRequest = 400 // RFC 7231, 6.5.1 StatusPaymentRequired = 402 // RFC 7231, 6.5.2 StatusForbidden = 403 // RFC 7231, 6.5.3 StatusNotFound = 404 // RFC 7231, 6.5.4 StatusMethodNotAllowed = 405 // RFC 7231, 6.5.5 StatusNotAcceptable = 406 // RFC 7231, 6.5.6 StatusProxyAuthRequired = 407 // RFC 7235, 3.2 StatusRequestTimeout = 408 // RFC 7231, 6.5.7 StatusConflict = 409 // RFC 7231, 6.5.8 StatusGone = 410 // RFC 7231, 6.5.9 StatusLengthRequired = 411 // RFC 7231, 6.5.10 StatusPreconditionFailed = 412 // RFC 7232, 4.2 StatusRequestEntityTooLarge = 413 // RFC 7231, 6.5.11 StatusRequestURITooLong = 414 // RFC 7231, 6.5.12 StatusUnsupportedMediaType = 415 // RFC 7231, 6.5.13 StatusRequestedRangeNotSatisfiable = 416 // RFC 7233, 4.4 StatusExpectationFailed = 417 // RFC 7231, 6.5.14 StatusTeapot = 418 // RFC 7168, 2.3.3 StatusMisdirectedRequest = 421 // RFC 7540, 9.1.2 StatusUnprocessableEntity = 422 // RFC 4918, 11.2 StatusLocked = 423 // RFC 4918, 11.3 StatusFailedDependency = 424 // RFC 4918, 11.4 StatusTooEarly = 425 // RFC 8470, 5.2. StatusUpgradeRequired = 426 // RFC 7231, 6.5.15 StatusPreconditionRequired = 428 // RFC 6585, 3 StatusTooManyRequests = 429 // RFC 6585, 4 StatusRequestHeaderFieldsTooLarge = 431 // RFC 6585, 5 StatusInternalServerError = 500 // RFC 7231, 6.6.1 StatusNotImplemented = 501 // RFC 7231, 6.6.2 StatusBadGateway = 502 // RFC 7231, 6.6.3 StatusGatewayTimeout = 504 // RFC 7231, 6.6.5 StatusHTTPVersionNotSupported = 505 // RFC 7231, 6.6.6 StatusVariantAlsoNegotiates = 506 // RFC 2295, 8.1 StatusInsufficientStorage = 507 // RFC 4918, 11.5 StatusLoopDetected = 508 // RFC 5842, 7.2 StatusNotExtended = 510 // RFC 2774, 7 StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6 )
HTTP status codes
const Version = "0.063"
Version is the current version of Zinc. This should be updated for each release.
Variables ¶
var ( ErrBadRequest = NewError(StatusBadRequest) // RFC 7231, 6.5.1 ErrPaymentRequired = NewError(StatusPaymentRequired) // RFC 7231, 6.5.2 ErrForbidden = NewError(StatusForbidden) // RFC 7231, 6.5.3 ErrNotFound = NewError(StatusNotFound) // RFC 7231, 6.5.4 ErrMethodNotAllowed = NewError(StatusMethodNotAllowed) // RFC 7231, 6.5.5 ErrNotAcceptable = NewError(StatusNotAcceptable) // RFC 7231, 6.5.6 ErrProxyAuthRequired = NewError(StatusProxyAuthRequired) // RFC 7235, 3.2 ErrRequestTimeout = NewError(StatusRequestTimeout) // RFC 7231, 6.5.7 ErrConflict = NewError(StatusConflict) // RFC 7231, 6.5.8 ErrGone = NewError(StatusGone) // RFC 7231, 6.5.9 ErrLengthRequired = NewError(StatusLengthRequired) // RFC 7231, 6.5.10 ErrPreconditionFailed = NewError(StatusPreconditionFailed) // RFC 7232, 4.2 ErrRequestEntityTooLarge = NewError(StatusRequestEntityTooLarge) // RFC 7231, 6.5.11 ErrRequestURITooLong = NewError(StatusRequestURITooLong) // RFC 7231, 6.5.12 ErrUnsupportedMediaType = NewError(StatusUnsupportedMediaType) // RFC 7231, 6.5.13 ErrRequestedRangeNotSatisfiable = NewError(StatusRequestedRangeNotSatisfiable) // RFC 7233, 4.4 ErrExpectationFailed = NewError(StatusExpectationFailed) // RFC 7231, 6.5.14 ErrTeapot = NewError(StatusTeapot) // RFC 7168, 2.3.3 ErrMisdirectedRequest = NewError(StatusMisdirectedRequest) // RFC 7540, 9.1.2 ErrUnprocessableEntity = NewError(StatusUnprocessableEntity) // RFC 4918, 11.2 ErrLocked = NewError(StatusLocked) // RFC 4918, 11.3 ErrFailedDependency = NewError(StatusFailedDependency) // RFC 4918, 11.4 ErrTooEarly = NewError(StatusTooEarly) // RFC 8470, 5.2. ErrUpgradeRequired = NewError(StatusUpgradeRequired) // RFC 7231, 6.5.15 ErrPreconditionRequired = NewError(StatusPreconditionRequired) // RFC 6585, 3 ErrTooManyRequests = NewError(StatusTooManyRequests) // RFC 6585, 4 ErrRequestHeaderFieldsTooLarge = NewError(StatusRequestHeaderFieldsTooLarge) // RFC 6585, 5 ErrInternalServerError = NewError(StatusInternalServerError) // RFC 7231, 6.6.1 ErrNotImplemented = NewError(StatusNotImplemented) // RFC 7231, 6.6.2 ErrBadGateway = NewError(StatusBadGateway) // RFC 7231, 6.6.3 ErrGatewayTimeout = NewError(StatusGatewayTimeout) // RFC 7231, 6.6.5 ErrHTTPVersionNotSupported = NewError(StatusHTTPVersionNotSupported) // RFC 7231, 6.6.6 ErrVariantAlsoNegotiates = NewError(StatusVariantAlsoNegotiates) // RFC 2295, 8.1 ErrInsufficientStorage = NewError(StatusInsufficientStorage) // RFC 4918, 11.5 ErrLoopDetected = NewError(StatusLoopDetected) // RFC 5842, 7.2 ErrNotExtended = NewError(StatusNotExtended) // RFC 2774, 7 ErrNetworkAuthenticationRequired = NewError(StatusNetworkAuthenticationRequired) // RFC 6585, 6 )
var DefaultConfig = Config{ DefaultAddr: "0.0.0.0:6538", ServerHeader: "Zinc/" + Version, AppName: "", AppVersion: Version, ShutdownTimeout: 10 * time.Second, ReadTimeout: 5 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 120 * time.Second, CaseSensitive: false, StrictRouting: false, BodyLimit: 4 * 1024 * 1024, Concurrency: 256 * 1024, EnableTrustedProxyCheck: false, TrustedProxies: []string{}, ProxyHeader: "X-Forwarded-For", DisableKeepalive: false, DisableDefaultContentType: false, RouteCacheSize: 1000, DisableStartupMessage: false, EnablePrintRoutes: false, }
DefaultConfig provides the default server configuration. It can be used as a base configuration for the server initialisation.
var ErrResponseAlreadySent = errors.New("response already sent")
Functions ¶
func ContextServiceOf ¶
ContextServiceOf is a helper function to retrieve a service by type from a Context Usage example: service, ok := zinc.ContextServiceOf[*UserService](c)
func GetVersionHeader ¶
func GetVersionHeader() string
GetVersionHeader returns the full version string for HTTP headers.
Types ¶
type App ¶
type App struct {
// contains filtered or unexported fields
}
func New ¶
New creates a new Zinc application instance with the specified configuration. If no configuration is provided, the default configuration is used.
func (*App) Connect ¶
func (a *App) Connect(path string, handlers ...RouteHandler) error
Connect registers a route for the CONNECT HTTP method.
func (*App) ConnectDB ¶
ConnectDB establishes a connection to the database and stores the pool. It requires the driver name (e.g., "postgres", "sqlite3") and the DSN. Remember to import the specific database driver in your main package (e.g., _ "github.com/lib/pq").
func (*App) Cron ¶
Cron adds a cron job to be executed on the given schedule Supports both error-returning and non-error-returning handlers
func (*App) Delete ¶
func (a *App) Delete(path string, handlers ...RouteHandler) error
Delete registers a route for the DELETE HTTP method.
func (*App) Get ¶
func (a *App) Get(path string, handlers ...RouteHandler) error
Get registers a route for the GET HTTP method.
func (*App) GetDB ¶
GetDB retrieves the configured database connection pool. Returns nil if no database connection has been established.
func (*App) GetService ¶
GetService retrieves a service by its concrete type Returns the service or nil if not found
func (*App) Head ¶
func (a *App) Head(path string, handlers ...RouteHandler) error
Head registers a route for the HEAD HTTP method.
func (*App) Injectable ¶
func (a *App) Injectable(service interface{})
Register registers a service with the application by its concrete type This allows for type-safe retrieval using GetService() later
func (*App) Options ¶
func (a *App) Options(path string, handlers ...RouteHandler) error
Options registers a route for the OPTIONS HTTP method.
func (*App) Patch ¶
func (a *App) Patch(path string, handlers ...RouteHandler) error
Patch registers a route for the PATCH HTTP method.
func (*App) Post ¶
func (a *App) Post(path string, handlers ...RouteHandler) error
Post registers a route for the POST HTTP method.
func (*App) Put ¶
func (a *App) Put(path string, handlers ...RouteHandler) error
Put registers a route for the PUT HTTP method.
func (*App) RemoveCRON ¶
RemoveCRON removes a scheduled job by ID
func (*App) ServeHTTP ¶
func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP is the default HTTP handler for the Zinc application.
func (*App) SetFileUpload ¶
func (a *App) SetFileUpload(upload *FileUpload)
SetFileUpload sets the file upload handler
func (*App) SetTemplateEngine ¶
func (a *App) SetTemplateEngine(engine *TemplateEngine)
SetTemplateEngine sets the template engine
func (*App) SetWebSocketHandler ¶
func (a *App) SetWebSocketHandler(handler *WebSocketHandler)
SetWebSocketHandler sets the WebSocket handler
func (*App) Trace ¶
func (a *App) Trace(path string, handlers ...RouteHandler) error
Trace registers a route for the TRACE HTTP method.
func (*App) Use ¶
func (a *App) Use(middleware ...Middleware)
Use adds middleware to the application
func (*App) Validate ¶
func (a *App) Validate(s any) ValidationErrors
Validate validates a struct using the validator
type BindOptions ¶
type BindOptions struct {
// DisableValidation disables validation after binding
DisableValidation bool
// DisableUnknownFields disables errors for unknown fields
DisableUnknownFields bool
}
BindOptions holds options for binding data
type Config ¶
type Config struct {
// Server configuration
// DefaultAddr specifies the HTTP server address.
// If not set, the server will listen on "0.0.0.0:6538".
DefaultAddr string
// ServerHeader sets the value of the Server HTTP header.
ServerHeader string
// AppName specifies the name of the application.
AppName string
// AppVersion specifies the version of the application.
AppVersion string
// Timeout settings
// ShutdownTimeout specifies the maximum duration to wait for server shutdown.
ShutdownTimeout time.Duration
// ReadTimeout is the maximum duration for reading the entire request.
ReadTimeout time.Duration
// WriteTimeout is the maximum duration before timing out writes of the response.
WriteTimeout time.Duration
// IdleTimeout is the maximum amount of time to wait for the next request.
IdleTimeout time.Duration
// Router settings
// CaseSensitive determines if routes should be case-sensitive.
// When false, /Foo and /foo are treated as the same route.
CaseSensitive bool
// StrictRouting determines if routes with trailing slashes are different than those without.
// When false, /api and /api/ are treated as the same route.
StrictRouting bool
// BodyLimit sets the maximum allowed size for a request body in bytes.
// Default is 4MB.
BodyLimit int64
// Concurrency sets the maximum number of concurrent connections.
Concurrency int
// EnableTrustedProxyCheck enables checking for trusted proxies
// when determining client IP addresses.
EnableTrustedProxyCheck bool
// TrustedProxies is a list of IP addresses or CIDR blocks that are trusted.
TrustedProxies []string
// ProxyHeader specifies which header to use for client IP address.
ProxyHeader string
// DisableKeepalive disables keep-alive connections.
DisableKeepalive bool
// DisableDefaultContentType disables sending the Content-Type header in responses
// when no content type is explicitly set.
DisableDefaultContentType bool
// Routing cache settings
// RouteCacheSize determines how many routes are stored in the route cache.
// Set to 0 to disable caching.
RouteCacheSize int
// Debug settings
// DisableStartupMessage disables the startup message when the server starts.
DisableStartupMessage bool
// EnablePrintRoutes enables printing all routes on startup.
EnablePrintRoutes bool
}
Config holds the server configuration parameters.
type Context ¶
type Context struct {
Response http.ResponseWriter
Request *http.Request
PathParams params
QueryParams url.Values
Method string
Store map[string]interface{}
// contains filtered or unexported fields
}
Context holds the context for a request. It is used to pass data between middleware and handlers.
func NewContext ¶
func NewContext(w http.ResponseWriter, r *http.Request) *Context
NewContext creates a new context for a request.
func (*Context) Bind ¶
func (c *Context) Bind(v interface{}, opts ...*BindOptions) error
Bind automatically binds request data based on Content-Type
func (*Context) BindForm ¶
func (c *Context) BindForm(v interface{}, opts ...*BindOptions) error
BindForm binds form data to the provided struct and validates it
func (*Context) BindJSON ¶
func (c *Context) BindJSON(v interface{}, opts ...*BindOptions) error
BindJSON binds the JSON request body to the provided struct and validates it
func (*Context) BindQuery ¶
func (c *Context) BindQuery(v interface{}, opts ...*BindOptions) error
BindQuery binds query parameters to the provided struct and validates it
func (*Context) BindXML ¶
func (c *Context) BindXML(v interface{}, opts ...*BindOptions) error
BindXML binds the XML request body to the provided struct and validates it
func (*Context) BodyParser ¶
BodyParser parses the request body into a provided struct.
func (*Context) BroadcastToRoom ¶
func (*Context) DB ¶
DB returns the database connection pool associated with the application. It returns nil if no database connection has been configured for the App.
func (*Context) File ¶
func (c *Context) File(name string) (*multipart.FileHeader, error)
File gets an uploaded file from the request
func (*Context) Files ¶
func (c *Context) Files(name string) ([]*multipart.FileHeader, error)
Files gets all uploaded files for a form field
func (*Context) FormFile ¶
func (c *Context) FormFile(name string) (*multipart.FileHeader, error)
FormFile returns the first file from the multipart form
func (*Context) FormFiles ¶
func (c *Context) FormFiles(name string) ([]*multipart.FileHeader, error)
FormFiles returns all files with the given field name
func (*Context) HasQuery ¶
Optimized method to check if a query parameter exists (avoids additional parsing)
func (*Context) SaveFile ¶
func (c *Context) SaveFile(fileHeader *multipart.FileHeader, dst string) error
SaveFile saves a file from a multipart form to the specified destination
func (*Context) Service ¶
func (c *Context) Service(name interface{}) interface{}
Service returns a service by name.
type CronJob ¶
type CronJob struct {
ID string
Schedule string
Handler func() error
// contains filtered or unexported fields
}
CronJob represents a single scheduled job
type CronScheduler ¶
type CronScheduler struct {
// contains filtered or unexported fields
}
CronScheduler manages all cron jobs
func (*CronScheduler) AddJob ¶
func (cs *CronScheduler) AddJob(id, schedule string, handler func() error) error
AddJob adds a new job to the scheduler
func (*CronScheduler) RemoveJob ¶
func (cs *CronScheduler) RemoveJob(id string)
RemoveJob removes a job from the scheduler
type DBRoutedHandler ¶
DBRoutedHandler defines a handler function that expects a Context and a DB connection.
type FileUpload ¶
FileUpload represents file upload configuration
func NewFileUpload ¶
func NewFileUpload(directory string) *FileUpload
NewFileUpload creates a new file upload handler
func (*FileUpload) SaveFile ¶
func (f *FileUpload) SaveFile(file *multipart.FileHeader) (string, error)
SaveFile saves an uploaded file
func (*FileUpload) SetAllowedTypes ¶
func (f *FileUpload) SetAllowedTypes(types []string)
SetAllowedTypes sets allowed file types
func (*FileUpload) SetMaxSize ¶
func (f *FileUpload) SetMaxSize(size int64)
SetMaxSize sets the maximum file size in bytes
type Group ¶
type Group struct {
// contains filtered or unexported fields
}
Group represents a group of routes with a common prefix and potentially shared middleware
func (*Group) Add ¶
func (g *Group) Add(method, path string, handlers ...RouteHandler) error
Add adds a route to the group with the given method and path
func (*Group) Connect ¶
func (g *Group) Connect(path string, handlers ...RouteHandler) error
Connect registers a route for the CONNECT HTTP method
func (*Group) Delete ¶
func (g *Group) Delete(path string, handlers ...RouteHandler) error
Delete registers a route for the DELETE HTTP method
func (*Group) Get ¶
func (g *Group) Get(path string, handlers ...RouteHandler) error
Get registers a route for the GET HTTP method
func (*Group) Head ¶
func (g *Group) Head(path string, handlers ...RouteHandler) error
Head registers a route for the HEAD HTTP method
func (*Group) Options ¶
func (g *Group) Options(path string, handlers ...RouteHandler) error
Options registers a route for the OPTIONS HTTP method
func (*Group) Patch ¶
func (g *Group) Patch(path string, handlers ...RouteHandler) error
Patch registers a route for the PATCH HTTP method
func (*Group) Post ¶
func (g *Group) Post(path string, handlers ...RouteHandler) error
Post registers a route for the POST HTTP method
func (*Group) Put ¶
func (g *Group) Put(path string, handlers ...RouteHandler) error
Put registers a route for the PUT HTTP method
func (*Group) Trace ¶
func (g *Group) Trace(path string, handlers ...RouteHandler) error
Trace registers a route for the TRACE HTTP method
func (*Group) Use ¶
func (g *Group) Use(middleware ...Middleware) *Group
Use adds middleware to the group
type HTTPError ¶
HTTPError represents an HTTP error with a status code and optional message.
func (*HTTPError) WithMessage ¶
WithMessage sets a custom message for the error.
type Middleware ¶
Middleware represents a function that can be used as middleware.
type Route ¶
type Route struct {
// contains filtered or unexported fields
}
Route represents a route in the router.
type RouteCache ¶
type RouteCache struct {
// contains filtered or unexported fields
}
RouteCache provides an LRU cache for routes.
func NewRouteCache ¶
func NewRouteCache(size int) *RouteCache
NewRouteCache creates a new route cache with the specified size.
type RouteHandler ¶
RouteHandler represents a function that handles a route request.
func StringHandler ¶
func StringHandler(str string) RouteHandler
StringHandler creates a RouteHandler that returns the provided string.
func WithDB ¶
func WithDB(handler DBRoutedHandler) RouteHandler
WithDB wraps a DBRoutedHandler, automatically providing the DB connection from the context. It returns a standard RouteHandler. If the DB connection is not available in the context, it returns a 500 error.
type RouteHandlerMap ¶
type RouteHandlerMap map[string]RouteHandler
RouteHandlerMap is a map of HTTP methods to route handlers.
type RouteNode ¶
type RouteNode struct {
// contains filtered or unexported fields
}
RouteNode represents a node in the route trie.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router handles HTTP routes and dispatches to the appropriate handler.
func (*Router) Add ¶
func (r *Router) Add(method, path string, handlers ...RouteHandler) error
Add adds a route to the router.
func (*Router) Find ¶
func (r *Router) Find(method, path string) (RouteHandler, *Context)
Find finds a route handler for the given method and path.
func (*Router) Use ¶
func (r *Router) Use(middleware ...Middleware)
Use adds middleware to the router.
type TemplateEngine ¶
type TemplateEngine struct {
// contains filtered or unexported fields
}
TemplateEngine handles template rendering with caching
func NewTemplateEngine ¶
func NewTemplateEngine(directory string) *TemplateEngine
NewTemplateEngine creates a new template engine
func (*TemplateEngine) AddFunc ¶
func (e *TemplateEngine) AddFunc(name string, fn interface{})
AddFunc adds a single template function
func (*TemplateEngine) ClearCache ¶
func (e *TemplateEngine) ClearCache()
ClearCache clears the template cache
func (*TemplateEngine) DisableCache ¶
func (e *TemplateEngine) DisableCache()
DisableCache disables template caching
func (*TemplateEngine) GetDirectory ¶
func (e *TemplateEngine) GetDirectory() string
GetDirectory returns the template directory path
func (*TemplateEngine) LoadTemplates ¶
func (e *TemplateEngine) LoadTemplates() error
LoadTemplates preloads all templates from the directory
func (*TemplateEngine) Render ¶
func (e *TemplateEngine) Render(w io.Writer, name string, data interface{}) error
Render renders a template with the given data
func (*TemplateEngine) SetExtension ¶
func (e *TemplateEngine) SetExtension(ext string)
SetExtension sets the template file extension
func (*TemplateEngine) SetFuncMap ¶
func (e *TemplateEngine) SetFuncMap(funcMap template.FuncMap)
SetFuncMap sets custom template functions
type ValidationError ¶
type ValidationErrors ¶
type ValidationErrors []ValidationError
func (ValidationErrors) Error ¶
func (ve ValidationErrors) Error() string
type Validator ¶
type Validator struct {
// contains filtered or unexported fields
}
func NewValidator ¶
func NewValidator() *Validator
func (*Validator) Validate ¶
func (v *Validator) Validate(s interface{}) ValidationErrors
type WebSocketHandler ¶
type WebSocketHandler struct {
// contains filtered or unexported fields
}
func WebSocket ¶
func WebSocket() *WebSocketHandler
func (*WebSocketHandler) BroadcastToRoom ¶
func (h *WebSocketHandler) BroadcastToRoom(roomID string, message []byte) error
func (*WebSocketHandler) HandleWebSocket ¶
func (h *WebSocketHandler) HandleWebSocket(c *Context) error