Documentation
¶
Overview ¶
Package nexora is a new Go framework focused on features and speed.
Index ¶
- Constants
- Variables
- func Debug(msg string, fields ...any)
- func Error(msg string, fields ...any)
- func Fatal(msg string, fields ...any)
- func Info(msg string, fields ...any)
- func InitDefaultLogger()
- func JSON[T any](c *Context) (*T, error)
- func Panic(msg string, fields ...any)
- func Param[T any](c *Context, name string) (T, error)
- func Query[T any](c *Context, name string) (T, error)
- func StatusText(code int) string
- func Trace(msg string, fields ...any)
- func Warn(msg string, fields ...any)
- func XML[T any](c *Context) (*T, error)
- type Binder
- type Config
- type Context
- func (c *Context) Abort()
- func (c *Context) AddHeader(key, value string)
- func (c *Context) BindForm(v any) error
- func (c *Context) BindJSON(v any) error
- func (c *Context) BindParams(v any) error
- func (c *Context) BindQuery(v any) error
- func (c *Context) BindXML(v any) error
- func (c *Context) Body() []byte
- func (c *Context) DelHeader(key string)
- func (c *Context) DeleteCookie(name, path, domain string)
- func (c *Context) GetCookie(name string) (string, error)
- func (c *Context) GetHeader(key string) string
- func (c *Context) Headers() http.Header
- func (c *Context) IP() string
- func (c *Context) IsAJAX() bool
- func (c *Context) Method() string
- func (c *Context) Nexora() *Nexora
- func (c *Context) Next() error
- func (c *Context) Param(name string, defaultValue ...string) string
- func (c *Context) ParamExists(name string) (string, bool)
- func (c *Context) Params() map[string]string
- func (c *Context) Path() string
- func (c *Context) Port() string
- func (c *Context) Queries() url.Values
- func (c *Context) Query(key string, defaultValue ...string) string
- func (c *Context) QueryArray(key string) []string
- func (c *Context) QueryExists(key string) (string, bool)
- func (c *Context) RealIP() string
- func (c *Context) RemotePort() string
- func (c *Context) Request() *http.Request
- func (c *Context) ResponseWriter() *ResponseWriter
- func (c *Context) SendByte(b []byte) error
- func (c *Context) SendBytes(b []byte) error
- func (c *Context) SendFile(filepath string) error
- func (c *Context) SendHeader(key string, value string) error
- func (c *Context) SendIndentJSON(v any, prefix, indent string) error
- func (c *Context) SendIndentXML(v any, prefix, indent string) error
- func (c *Context) SendJSON(v any) error
- func (c *Context) SendJsonp(callback string, v any) error
- func (c *Context) SendPrettyJSON(v any) error
- func (c *Context) SendPrettyXML(v any) error
- func (c *Context) SendSecureJSON(v any) error
- func (c *Context) SendStatus(code int) error
- func (c *Context) SendString(s string) error
- func (c *Context) SendXML(v any) error
- func (c *Context) SetContentType(ct string)
- func (c *Context) SetCookie(cookie *Cookie)
- func (c *Context) SetHeader(key, value string)
- func (c *Context) Status(code int) *Context
- type Cookie
- type DecoderFunc
- type EncoderFunc
- type HTTPError
- type Handler
- type IndentationEncoder
- type LoggerConfig
- type Nexora
- type ResponseWriter
- type Route
- func (r *Route) Connect(handlers ...Handler) *Route
- func (r *Route) Delete(handlers ...Handler) *Route
- func (r *Route) Get(handlers ...Handler) *Route
- func (r *Route) Handle(method string, handlers ...Handler) *Route
- func (r *Route) Head(handlers ...Handler) *Route
- func (r *Route) Method() string
- func (r *Route) Name(name string) *Route
- func (r *Route) Options(handlers ...Handler) *Route
- func (r *Route) Patch(handlers ...Handler) *Route
- func (r *Route) Path() string
- func (r *Route) Post(handlers ...Handler) *Route
- func (r *Route) Put(handlers ...Handler) *Route
- func (r *Route) String() string
- func (r *Route) Tag(value any) *Route
- func (r *Route) Tags() []any
- func (r *Route) Trace(handlers ...Handler) *Route
- func (r *Route) URL(pairs ...any) (s string)
- type RouteGroup
- func (g *RouteGroup) Connect(path string, handler ...Handler) *Route
- func (g *RouteGroup) Delete(path string, handler ...Handler) *Route
- func (g *RouteGroup) Get(path string, handler ...Handler) *Route
- func (g *RouteGroup) Group(prefix string, handlers ...Handler) *RouteGroup
- func (g *RouteGroup) Head(path string, handler ...Handler) *Route
- func (g *RouteGroup) Options(path string, handler ...Handler) *Route
- func (g *RouteGroup) Patch(path string, handler ...Handler) *Route
- func (g *RouteGroup) Post(path string, handler ...Handler) *Route
- func (g *RouteGroup) Put(path string, handler ...Handler) *Route
- func (g *RouteGroup) Trace(path string, handler ...Handler) *Route
- func (g *RouteGroup) Use(handlers ...Handler)
Constants ¶
const ( ContentTypeOctetStream = "application/octet-stream" ContentTypeJSON = "application/json" ContentTypeXML = "application/xml" )
const ( // HeaderAccept specifies media types acceptable for the response. HeaderAccept = "Accept" // HeaderAcceptCharset specifies acceptable character sets. HeaderAcceptCharset = "Accept-Charset" // HeaderAcceptEncoding specifies acceptable content encodings (e.g., gzip, deflate). HeaderAcceptEncoding = "Accept-Encoding" // HeaderAcceptLanguage specifies preferred natural languages for the response. HeaderAcceptLanguage = "Accept-Language" // HeaderAcceptRanges indicates that the server supports range requests. HeaderAcceptRanges = "Accept-Ranges" // HeaderAccessControlAllowOrigin specifies the origins that are allowed to access the resource. HeaderAccessControlAllowOrigin = "Access-Control-Allow-Origin" // HeaderAccessControlAllowMethods specifies the HTTP methods allowed when accessing the resource. HeaderAccessControlAllowMethods = "Access-Control-Allow-Methods" // HeaderAccessControlAllowHeaders specifies which headers can be used during the actual request. HeaderAccessControlAllowHeaders = "Access-Control-Allow-Headers" // HeaderAccessControlExposeHeaders indicates which headers can be exposed to the client. HeaderAccessControlExposeHeaders = "Access-Control-Expose-Headers" // HeaderAccessControlMaxAge indicates how long the results of a preflight request can be cached. HeaderAccessControlMaxAge = "Access-Control-Max-Age" // HeaderAccessControlRequestMethod is used in preflight requests to specify the method being used. HeaderAccessControlRequestMethod = "Access-Control-Request-Method" // HeaderAccessControlRequestHeaders is used in preflight requests to indicate which HTTP headers will be used. HeaderAccessControlRequestHeaders = "Access-Control-Request-Headers" // HeaderAge indicates the age of the object in a cache. HeaderAge = "Age" // HeaderAllow lists the allowed methods for a resource. HeaderAllow = "Allow" // HeaderAuthorization contains credentials for authenticating the user agent. HeaderAuthorization = "Authorization" // HeaderCacheControl specifies directives for caching mechanisms. HeaderCacheControl = "Cache-Control" // HeaderConnection controls whether the network connection stays open after the transaction finishes. HeaderConnection = "Connection" // HeaderContentDisposition indicates if the content should be displayed inline or as an attachment. HeaderContentDisposition = "Content-Disposition" // HeaderContentEncoding specifies the encoding used on the data. HeaderContentEncoding = "Content-Encoding" // HeaderContentLanguage describes the natural language(s) of the intended audience. HeaderContentLanguage = "Content-Language" // HeaderContentLength indicates the size of the message body. HeaderContentLength = "Content-Length" // HeaderContentLocation indicates an alternate location for the returned data. HeaderContentLocation = "Content-Location" // HeaderContentRange specifies where in a full body message a partial message belongs. HeaderContentRange = "Content-Range" // HeaderContentType indicates the media type of the resource. HeaderContentType = "Content-Type" // HeaderCookie contains stored HTTP cookies previously sent by the server. HeaderCookie = "Cookie" // HeaderDate represents the date and time at which the message was originated. HeaderDate = "Date" // HeaderETag is a unique identifier for a specific version of a resource. HeaderETag = "ETag" // HeaderExpect indicates expectations that need to be fulfilled before sending the request body. HeaderExpect = "Expect" // HeaderExpires gives the date/time after which the response is considered stale. HeaderExpires = "Expires" // HeaderForwarded is used to identify the originating IP address of a client. HeaderForwarded = "Forwarded" // HeaderFrom indicates the email address of the user making the request. HeaderFrom = "From" // HeaderHost specifies the domain name of the server and optionally the port. HeaderHost = "Host" // HeaderIfMatch makes the request conditional on the resource matching a given ETag. HeaderIfMatch = "If-Match" // HeaderIfModifiedSince makes the request conditional: it will only be successful if the resource has been modified since the given date. HeaderIfModifiedSince = "If-Modified-Since" // HeaderIfNoneMatch makes the request conditional: it will only be successful if the resource does not match the given ETag(s). HeaderIfNoneMatch = "If-None-Match" // HeaderIfRange makes a range request conditional based on ETag or modification date. HeaderIfRange = "If-Range" // HeaderIfUnmodifiedSince makes the request conditional: it will only be successful if the resource has not been modified since the given date. HeaderIfUnmodifiedSince = "If-Unmodified-Since" // HeaderLastModified indicates the date and time the resource was last modified. HeaderLastModified = "Last-Modified" // HeaderLink provides links to related resources. HeaderLink = "Link" // HeaderLocation indicates the URL to redirect a page to. HeaderLocation = "Location" // HeaderMaxForwards is used with TRACE and OPTIONS to limit the number of times a message can be forwarded. HeaderMaxForwards = "Max-Forwards" // HeaderOrigin indicates where the request originated (used in CORS). HeaderOrigin = "Origin" // HeaderPragma includes implementation-specific directives that may apply to any recipient along the request/response chain. HeaderPragma = "Pragma" // HeaderProxyAuthenticate defines the authentication method that should be used to access a resource behind a proxy. HeaderProxyAuthenticate = "Proxy-Authenticate" // HeaderProxyAuthorization contains credentials to authenticate a user agent with a proxy server. HeaderProxyAuthorization = "Proxy-Authorization" // HeaderRange specifies the range of bytes a client is requesting. HeaderRange = "Range" // HeaderReferer indicates the address of the previous web page from which a link to the currently requested page was followed. HeaderReferer = "Referer" // HeaderRetryAfter indicates how long the user agent should wait before making a follow-up request. HeaderRetryAfter = "Retry-After" // HeaderServer contains information about the software used by the origin server. HeaderServer = "Server" // HeaderSetCookie sends cookies from the server to the user agent. HeaderSetCookie = "Set-Cookie" // HeaderTE indicates what transfer encodings the client is willing to accept. HeaderTE = "TE" // HeaderTrailer indicates which headers will be present in the trailer part of the message. HeaderTrailer = "Trailer" // HeaderTransferEncoding specifies the form of encoding used to safely transfer the entity to the user. HeaderTransferEncoding = "Transfer-Encoding" // HeaderUpgrade is used to switch protocols (e.g., from HTTP/1.1 to WebSockets). HeaderUpgrade = "Upgrade" // HeaderUserAgent contains information about the user agent originating the request. HeaderUserAgent = "User-Agent" // HeaderVary indicates which headers a cache should use to decide if a cached response is fresh. HeaderVary = "Vary" // HeaderVia shows intermediate protocols and recipients between the user agent and server. HeaderVia = "Via" // HeaderWarning carries additional information about the status or transformation of a message. HeaderWarning = "Warning" // HeaderWWWAuthenticate indicates the authentication method that should be used to access a resource. HeaderWWWAuthenticate = "WWW-Authenticate" // HeaderAIM is a Microsoft extension for incremental GETs. HeaderAIM = "A-IM" // HeaderAcceptDatetime is used to request responses based on modification date (used in some APIs). HeaderAcceptDatetime = "Accept-Datetime" // HeaderAccessControlAllowCredentials indicates whether the response to the request can be exposed when credentials are present. HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials" // HeaderAccessControlRequestCredentials is a non-standard header for requesting with credentials. HeaderAccessControlRequestCredentials = "Access-Control-Request-Credentials" // HeaderContentSecurityPolicy defines security policies (e.g., scripts, styles, etc.). HeaderContentSecurityPolicy = "Content-Security-Policy" // HeaderContentMD5 is a base64-encoded 128-bit MD5 digest of the message body. HeaderContentMD5 = "Content-MD5" // HeaderDNT indicates the user’s tracking preference (Do Not Track). HeaderDNT = "DNT" // HeaderDigest provides a message digest for the resource. HeaderDigest = "Digest" // HeaderEarlyData indicates if early data (0-RTT) is accepted. HeaderEarlyData = "Early-Data" // HeaderExpectCT allows sites to opt in to reporting of Certificate Transparency violations. HeaderExpectCT = "Expect-CT" // HeaderForwardedFor indicates the original IP address of a client connecting through a proxy. HeaderForwardedFor = "X-Forwarded-For" // HeaderForwardedHost indicates the original host requested by the client in the Host HTTP request header. HeaderForwardedHost = "X-Forwarded-Host" // HeaderForwardedProto indicates the originating protocol (HTTP or HTTPS). HeaderForwardedProto = "X-Forwarded-Proto" // HeaderHTTP2Settings is used in HTTP/2 to carry connection-specific settings. HeaderHTTP2Settings = "HTTP2-Settings" // HeaderKeepAlive specifies parameters for a persistent connection. HeaderKeepAlive = "Keep-Alive" // HeaderNEL reports network errors to a reporting endpoint. HeaderNEL = "NEL" // HeaderOriginTrial is used by Chrome to enable experimental web platform features. HeaderOriginTrial = "Origin-Trial" // HeaderPermissionsPolicy allows a server to declare permissions for APIs and features. HeaderPermissionsPolicy = "Permissions-Policy" // HeaderProxyConnection is a non-standard header used by some proxies. HeaderProxyConnection = "Proxy-Connection" // HeaderPublicKeyPins was used for Public Key Pinning (now deprecated). HeaderPublicKeyPins = "Public-Key-Pins" // HeaderReferrerPolicy specifies the referrer information sent with requests. HeaderReferrerPolicy = "Referrer-Policy" // HeaderReportTo specifies where reports should be sent in Reporting API. HeaderReportTo = "Report-To" // HeaderRequestID is used for request tracing (custom header). HeaderRequestID = "X-Request-ID" // HeaderSaveData indicates user preference for reduced data usage. HeaderSaveData = "Save-Data" // HeaderSourceMap indicates where source maps are located for debugging. HeaderSourceMap = "SourceMap" // HeaderStrictTransportSecurity enforces HTTPS communication with the server. HeaderStrictTransportSecurity = "Strict-Transport-Security" // HeaderTimingAllowOrigin specifies origins that are allowed to see timing information. HeaderTimingAllowOrigin = "Timing-Allow-Origin" // HeaderUpgradeInsecureRequests indicates that the client prefers secure content. HeaderUpgradeInsecureRequests = "Upgrade-Insecure-Requests" // HeaderXContentTypeOptions prevents MIME-sniffing (e.g., nosniff). HeaderXContentTypeOptions = "X-Content-Type-Options" // HeaderXDNSPrefetchControl controls DNS prefetching. HeaderXDNSPrefetchControl = "X-DNS-Prefetch-Control" // HeaderXDownloadOptions prevents automatic file opening in older browsers. HeaderXDownloadOptions = "X-Download-Options" // HeaderXFrameOptions prevents clickjacking by controlling frame usage. HeaderXFrameOptions = "X-Frame-Options" // HeaderXPermittedCrossDomainPolicies controls Adobe Flash and Acrobat access. HeaderXPermittedCrossDomainPolicies = "X-Permitted-Cross-Domain-Policies" // HeaderXPoweredBy is used to indicate the technology used (e.g., Express, PHP). HeaderXPoweredBy = "X-Powered-By" // HeaderXRequestID is a duplicate of X-Request-ID, used in some tracing setups. HeaderXRequestID = "X-Request-ID" // HeaderXUACompatible specifies compatibility mode for IE/Edge. HeaderXUACompatible = "X-UA-Compatible" // HeaderXXSSProtection enables cross-site scripting (XSS) filters. HeaderXXSSProtection = "X-XSS-Protection" // HeaderXRequestedWith is a non-standard header used to identify AJAX (XHR) requests. // Commonly set to "XMLHttpRequest" by client-side libraries like jQuery. HeaderXRequestedWith = "X-Requested-With" )
const ( MethodGet = "GET" MethodHead = "HEAD" MethodPost = "POST" MethodPut = "PUT" MethodPatch = "PATCH" // RFC 5789 MethodDelete = "DELETE" MethodConnect = "CONNECT" MethodOptions = "OPTIONS" MethodTrace = "TRACE" )
Taken from net/http package in Go standard library
const ( Reset = "\033[0m" Red = "\033[31m" Green = "\033[32m" Yellow = "\033[33m" Blue = "\033[34m" Purple = "\033[35m" Cyan = "\033[36m" White = "\033[37m" )
ANSI color codes
const ( StatusContinue = 100 // RFC 9110, 15.2.1 StatusSwitchingProtocols = 101 // RFC 9110, 15.2.2 StatusProcessing = 102 // RFC 2518, 10.1 StatusEarlyHints = 103 // RFC 8297 StatusOK = 200 // RFC 9110, 15.3.1 StatusCreated = 201 // RFC 9110, 15.3.2 StatusAccepted = 202 // RFC 9110, 15.3.3 StatusNonAuthoritativeInfo = 203 // RFC 9110, 15.3.4 StatusNoContent = 204 // RFC 9110, 15.3.5 StatusResetContent = 205 // RFC 9110, 15.3.6 StatusPartialContent = 206 // RFC 9110, 15.3.7 StatusMultiStatus = 207 // RFC 4918, 11.1 StatusAlreadyReported = 208 // RFC 5842, 7.1 StatusIMUsed = 226 // RFC 3229, 10.4.1 StatusMultipleChoices = 300 // RFC 9110, 15.4.1 StatusMovedPermanently = 301 // RFC 9110, 15.4.2 StatusFound = 302 // RFC 9110, 15.4.3 StatusSeeOther = 303 // RFC 9110, 15.4.4 StatusNotModified = 304 // RFC 9110, 15.4.5 StatusUseProxy = 305 // RFC 9110, 15.4.6 StatusTemporaryRedirect = 307 // RFC 9110, 15.4.8 StatusPermanentRedirect = 308 // RFC 9110, 15.4.9 StatusBadRequest = 400 // RFC 9110, 15.5.1 StatusPaymentRequired = 402 // RFC 9110, 15.5.3 StatusForbidden = 403 // RFC 9110, 15.5.4 StatusNotFound = 404 // RFC 9110, 15.5.5 StatusMethodNotAllowed = 405 // RFC 9110, 15.5.6 StatusNotAcceptable = 406 // RFC 9110, 15.5.7 StatusProxyAuthRequired = 407 // RFC 9110, 15.5.8 StatusRequestTimeout = 408 // RFC 9110, 15.5.9 StatusConflict = 409 // RFC 9110, 15.5.10 StatusGone = 410 // RFC 9110, 15.5.11 StatusLengthRequired = 411 // RFC 9110, 15.5.12 StatusPreconditionFailed = 412 // RFC 9110, 15.5.13 StatusRequestEntityTooLarge = 413 // RFC 9110, 15.5.14 StatusRequestURITooLong = 414 // RFC 9110, 15.5.15 StatusUnsupportedMediaType = 415 // RFC 9110, 15.5.16 StatusRequestedRangeNotSatisfiable = 416 // RFC 9110, 15.5.17 StatusExpectationFailed = 417 // RFC 9110, 15.5.18 StatusTeapot = 418 // RFC 9110, 15.5.19 (Unused) StatusMisdirectedRequest = 421 // RFC 9110, 15.5.20 StatusUnprocessableEntity = 422 // RFC 9110, 15.5.21 StatusLocked = 423 // RFC 4918, 11.3 StatusFailedDependency = 424 // RFC 4918, 11.4 StatusTooEarly = 425 // RFC 8470, 5.2. StatusUpgradeRequired = 426 // RFC 9110, 15.5.22 StatusPreconditionRequired = 428 // RFC 6585, 3 StatusTooManyRequests = 429 // RFC 6585, 4 StatusRequestHeaderFieldsTooLarge = 431 // RFC 6585, 5 StatusInternalServerError = 500 // RFC 9110, 15.6.1 StatusNotImplemented = 501 // RFC 9110, 15.6.2 StatusBadGateway = 502 // RFC 9110, 15.6.3 StatusGatewayTimeout = 504 // RFC 9110, 15.6.5 StatusHTTPVersionNotSupported = 505 // RFC 9110, 15.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 )
Taken from net/http package in Go standard library HTTP status codes as registered with IANA. See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const MethodWild = "*"
MethodWild wild HTTP method
Variables ¶
var ( ErrBadRequest = NewHTTPError(StatusBadRequest, "Bad Request") ErrPaymentRequired = NewHTTPError(StatusPaymentRequired, "Payment Required") ErrForbidden = NewHTTPError(StatusForbidden, "Forbidden") ErrNotFound = NewHTTPError(StatusNotFound, "Not Found") ErrMethodNotAllowed = NewHTTPError(StatusMethodNotAllowed, "Method Not Allowed") ErrNotAcceptable = NewHTTPError(StatusNotAcceptable, "Not Acceptable") ErrProxyAuthRequired = NewHTTPError(StatusProxyAuthRequired, "Proxy Authentication Required") ErrRequestTimeout = NewHTTPError(StatusRequestTimeout, "Request Timeout") ErrConflict = NewHTTPError(StatusConflict, "Conflict") ErrGone = NewHTTPError(StatusGone, "Gone") ErrLengthRequired = NewHTTPError(StatusLengthRequired, "Length Required") ErrPreconditionFailed = NewHTTPError(StatusPreconditionFailed, "Precondition Failed") ErrRequestEntityTooLarge = NewHTTPError(StatusRequestEntityTooLarge, "Payload Too Large") ErrRequestURITooLong = NewHTTPError(StatusRequestURITooLong, "URI Too Long") ErrUnsupportedMediaType = NewHTTPError(StatusUnsupportedMediaType, "Unsupported Media Type") ErrRequestedRangeNotSatisfiable = NewHTTPError(StatusRequestedRangeNotSatisfiable, "Range Not Satisfiable") ErrExpectationFailed = NewHTTPError(StatusExpectationFailed, "Expectation Failed") ErrTeapot = NewHTTPError(StatusTeapot, "I'm a teapot") ErrMisdirectedRequest = NewHTTPError(StatusMisdirectedRequest, "Misdirected Request") ErrUnprocessableEntity = NewHTTPError(StatusUnprocessableEntity, "Unprocessable Entity") ErrLocked = NewHTTPError(StatusLocked, "Locked") ErrFailedDependency = NewHTTPError(StatusFailedDependency, "Failed Dependency") ErrTooEarly = NewHTTPError(StatusTooEarly, "Too Early") ErrUpgradeRequired = NewHTTPError(StatusUpgradeRequired, "Upgrade Required") ErrPreconditionRequired = NewHTTPError(StatusPreconditionRequired, "Precondition Required") ErrTooManyRequests = NewHTTPError(StatusTooManyRequests, "Too Many Requests") ErrRequestHeaderFieldsTooLarge = NewHTTPError(StatusRequestHeaderFieldsTooLarge, "Request Header Fields Too Large") ErrInternalServerError = NewHTTPError(StatusInternalServerError, "Internal Server Error") ErrNotImplemented = NewHTTPError(StatusNotImplemented, "Not Implemented") ErrBadGateway = NewHTTPError(StatusBadGateway, "Bad Gateway") ErrGatewayTimeout = NewHTTPError(StatusGatewayTimeout, "Gateway Timeout") ErrHTTPVersionNotSupported = NewHTTPError(StatusHTTPVersionNotSupported, "HTTP Version Not Supported") ErrVariantAlsoNegotiates = NewHTTPError(StatusVariantAlsoNegotiates, "Variant Also Negotiates") ErrInsufficientStorage = NewHTTPError(StatusInsufficientStorage, "Insufficient Storage") ErrLoopDetected = NewHTTPError(StatusLoopDetected, "Loop Detected") ErrNotExtended = NewHTTPError(StatusNotExtended, "Not Extended") ErrNetworkAuthenticationRequired = NewHTTPError(StatusNetworkAuthenticationRequired, "Network Authentication Required") )
Functions ¶
func InitDefaultLogger ¶
func InitDefaultLogger()
InitDefaultLogger initializes the logger with default configuration. This should be called if no custom LoggerConfig is provided.
func JSON ¶
JSON is a helper function that parses the JSON body of the request into a new instance of type T, reducing boilerplate code.
func Param ¶
Param is a generic function that retrieves a URL parameter by name and converts it to the specified type T.
It supports the following types: string, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, and bool.
Returns the converted value and an error if the parameter is not found or fails to convert.
func Query ¶
Query is a generic function that retrieves a URL query parameter by name and converts it to the specified type T.
It supports the following types: string, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, and bool.
Returns the converted value and an error if the parameter is not found or fails to convert.
func StatusText ¶
StatusText returns a text for the HTTP status code. It returns the empty string if the code is unknown.
Types ¶
type Binder ¶
type Binder struct {
// contains filtered or unexported fields
}
Binder holds separate decoders for query and form data.
func (*Binder) DecodeForm ¶
DecodeForm decodes form data into the provided struct.
type Config ¶
type Config struct {
LoggerConfig *LoggerConfig
RouteGroup // Default route group for new routes
JSONEncoder EncoderFunc // This will be used to encode json payload
JSONDecoder DecoderFunc // This will be used to decode json playload
// secureJsonPrefix is the prefix added when sending JSON with c.SendSecureJson.
// It helps prevent JSON hijacking attacks by making the response invalid JavaScript
// until parsed as JSON. The default value is "while(1);".
SecureJSONPrefix string
JSONIndentationEncoder IndentationEncoder // JsonIndentationEncoder encodes a value as indented JSON.
XMLEncoder EncoderFunc // Encodes a Go value into XML.
XMLDecoder DecoderFunc // Decodes XML data into a Go value.
XMLIndentationEncoder IndentationEncoder // Encodes a Go value into indented XML.
// Enables automatic redirection if the current route can't be matched but a
// handler for the path with (without) the trailing slash exists.
// For example if /foo/ is requested but a route only exists for /foo, the
// client is redirected to /foo with http status code 301 for GET requests
// and 308 for all other request methods.
RedirectTrailingSlash *bool
// If enabled, the router tries to fix the current request path, if no
// handle is registered for it.
// First superfluous path elements like ../ or // are removed.
// Afterwards the router does a case-insensitive lookup of the cleaned path.
// If a handle can be found for this route, the router makes a redirection
// to the corrected path with status code 301 for GET requests and 308 for
// all other request methods.
// For example /FOO and /..//Foo could be redirected to /foo.
// RedirectTrailingSlash is independent of this option.
RedirectFixedPath *bool
// If enabled, the router checks if another method is allowed for the
// current route, if the current request can not be routed.
// If this is the case, the request is answered with 'Method Not Allowed'
// and HTTP status code 405.
// If no other Method is allowed, the request is delegated to the NotFound
// handler.
HandleMethodNotAllowed *bool
// If enabled, the router automatically replies to OPTIONS requests.
// Custom OPTIONS handlers take priority over automatic replies.
HandleOPTIONS *bool
// An optional http.Handler that is called on automatic OPTIONS requests.
// The handler is only called if HandleOPTIONS is true and no OPTIONS
// handler for the specific path was set.
// The "Allowed" header is set before calling the handler.
GlobalOPTIONS Handler
// Configurable http.Handler which is called when no matching route is
// found. If it is not set, default NotFound is used.
NotFound Handler
// Configurable http.Handler which is called when a request
// cannot be routed and HandleMethodNotAllowed is true.
// If it is not set, ctx.Error with http.StatusMethodNotAllowed is used.
// The "Allow" header with allowed request methods is set before the handler
// is called.
MethodNotAllowed Handler
// Function to handle panics recovered from http handlers.
// It should be used to generate a error page and return the http error code
// 500 (Internal Server Error).
// The handler can be used to keep your server from crashing because of
// unrecovered panics.
PanicHandler func(c *Context, v any) error
ErrorHandler func(c *Context, err error) error
// BodyLimit is the maximum size for a request body. The default is 4MB.
BodyLimit int64
// contains filtered or unexported fields
}
Config holds all configurable options for Nexora. Users can pass a Config to New() to override defaults.
func DefaultConfig ¶
func DefaultConfig() *Config
DefaultConfig returns a Config with sensible default values.
type Context ¶
type Context struct {
// contains filtered or unexported fields
}
Context represents the context of a single HTTP request in the Nexora framework.
It contains the HTTP request, response writer, URL parameters, and the middleware handler chain. Context provides helper methods for accessing request data, sending responses, and controlling request flow (e.g., aborting or continuing handler execution).
func (*Context) Abort ¶
func (c *Context) Abort()
Abort stops the execution of any remaining handlers in the chain.
func (*Context) AddHeader ¶
AddHeader adds the specified value to the given header field in the HTTP response. It appends to any existing values associated with the key.
func (*Context) BindParams ¶
BindParams binds the URL parameters to the fields of a struct. The struct fields must be exported and have a `param` tag.
func (*Context) Body ¶
Body returns the raw request body as []byte. It reads and caches the body so multiple calls won't re-read the stream.
func (*Context) DelHeader ¶
DelHeader deletes the specified header field from the HTTP response. If the header is not present, this is a no-op.
func (*Context) DeleteCookie ¶
DeleteCookie removes a cookie by setting its MaxAge to -1 and expiration to the Unix epoch.
Parameters:
- name: the name of the cookie to delete.
- path: the cookie path (usually "/" for global).
- domain: the cookie domain.
Example:
c.DeleteCookie("session_id", "/", "example.com")
func (*Context) GetCookie ¶
GetCookie retrieves a cookie value from the HTTP request by its name.
Parameters:
- name: the name of the cookie to retrieve.
Returns:
- string: the value of the cookie.
- error: if the cookie is not found or any other error occurs.
Example:
value, err := c.GetCookie("session_id")
if err != nil {
// handle missing cookie
}
func (*Context) GetHeader ¶
GetHeader retrieves the value of the specified request header field. If the header is not present, it returns an empty string.
func (*Context) Headers ¶
Headers returns all the HTTP request headers as an http.Header map. The returned map can be iterated or queried for multiple values.
func (*Context) IP ¶
IP returns the remote IP address of the client that made the request. If the remote address cannot be parsed, it returns an empty string.
func (*Context) Next ¶
Next executes the next handler in the middleware chain.
If a handler returns an error, execution is halted and the error is returned. If all handlers run successfully, it returns nil.
func (*Context) Param ¶
Param returns the value of a route parameter by name.
If the parameter is not present and a defaultValue is provided, the first element of defaultValue is returned instead.
Example usage:
id := ctx.Param("id") // returns "" if not found
id := ctx.Param("id", "default") // returns "default" if not found.
func (*Context) ParamExists ¶
ParamExists returns the value of a route parameter and a boolean indicating whether the parameter was present in the route.
This is useful when you need to distinguish between a parameter that is missing and one that is present with an empty value.
Example usage:
id, ok := ctx.ParamExists("id")
if ok {
// Use id
} else {
// Handle missing parameter
}
func (*Context) Port ¶
Port returns the server port on which the request was received. It parses the Host field of the request to extract the port. If no explicit port is present, it falls back to 443 for HTTPS or 80 for HTTP.
func (*Context) Queries ¶
Queries returns all URL query parameters as a url.Values map. It ensures the query parameters are parsed and cached first.
Example:
values := c.Queries()
name := values.Get("name")
func (*Context) Query ¶
Query returns the first value for a given query parameter key. If the key is not present, it returns the optional defaultValue if provided, or an empty string otherwise.
Example:
q := c.Query("q")
page := c.Query("page", "1") // default to "1" if missing
func (*Context) QueryArray ¶
QueryArray returns all values for a given query parameter key. If the key is not present, it returns nil.
Example:
tags := c.QueryArray("tag")
// ?tag=go&tag=web → []string{"go", "web"}
func (*Context) QueryExists ¶
QueryExists returns the first value for the given query key and a boolean indicating whether the key exists.
If the key is present in the query parameters (even if its value is empty), it returns (value, true). If the key is not present, it returns ("", false).
Example:
?foo=bar -> ("bar", true)
?foo= -> ("", true)
(no foo) -> ("", false)
func (*Context) RemotePort ¶
RemotePort returns the remote TCP port from which the client is connected. If the remote address cannot be parsed, it returns an empty string.
func (*Context) ResponseWriter ¶
func (c *Context) ResponseWriter() *ResponseWriter
ResponseWriter returns the custom ResponseWriter used to send the response.
func (*Context) SendByte ¶
SendByte writes the given byte slice to the HTTP response without modifying the Content-Type. Returns an HTTP error if writing fails or not all bytes are sent.
For sending a single byte, consider using SendBytes([]byte{b}).
func (*Context) SendBytes ¶
SendBytes sets the Content-Type to "application/octet-stream" and writes the given byte slice to the HTTP response. Returns an HTTP error if writing fails or not all bytes are sent.
func (*Context) SendFile ¶
SendFile sends a file. It uses http.ServeContent to efficiently send the file, handling details like Content-Type, ETag, and Range requests.
func (*Context) SendHeader ¶
SendHeader sets an HTTP header key-value pair on the response.
This method is **sugar syntax**: it always returns `error` (currently always `nil`), which matches the typical handler signature in this framework (e.g., `func(c *Context) error`). That means you can directly return it from your handler without extra wrapping.
Example:
func H(c *nexora.Context) error {
// Set a custom header and directly return
return c.SendHeader("X-Custom-Header", "my-value")
}
Parameters:
- key: The header name (e.g., "X-Custom-Header").
- value: The header value.
Returns:
- error: Always returns nil (reserved for future use).
func (*Context) SendIndentJSON ¶
SendIndentJSON encodes the given value `v` into indented JSON using the provided prefix and indent string. It sets the response Content-Type to "application/json" and writes the JSON body to the response.
Parameters:
- v: The value to encode as JSON.
- prefix: A string to place before each JSON line.
- indent: A string used for indentation (e.g., " " or " ").
Returns an error if JSON encoding or writing to the response fails.
func (*Context) SendIndentXML ¶
SendIndentXML encodes the given value `v` into indented XML using the provided prefix and indent string. It sets the response Content-Type to "application/xml" and writes the XML body to the response.
Parameters:
- v: The value to encode as XML.
- prefix: A string to place before each XML line.
- indent: A string used for indentation (e.g., " " or " ").
Returns an error if XML encoding or writing to the response fails.
func (*Context) SendJSON ¶
SendJSON encodes v as JSON and writes it to the response body. Returns an error if encoding fails.
func (*Context) SendJsonp ¶
SendJsonp encodes v as JSON and wraps it in a JavaScript function call using the given callback name (e.g., callback(v);). This is commonly used to support cross-domain requests without CORS.
Example output:
callback({"message":"hello"});
If encoding fails or writing fails, an HTTP error is returned.
func (*Context) SendPrettyJSON ¶
SendPrettyJSON encodes the given value `v` into a human-readable JSON format (pretty-printed with a single space as indentation). It sets the response Content-Type to "application/json" and writes the JSON body to the response.
Returns an error if JSON encoding or writing to the response fails.
func (*Context) SendPrettyXML ¶
SendPrettyXML encodes the given value `v` into a human-readable XML format (pretty-printed with a single space as indentation). It sets the response Content-Type to "application/xml" and writes the XML body to the response.
Returns an error if XML encoding or writing to the response fails.
func (*Context) SendSecureJSON ¶
SendSecureJSON encodes the given value as JSON and writes it to the response with the "application/json" Content-Type header. The output is prefixed with c.nexora.secureJsonPrefix (e.g., "while(1);") to mitigate JSON hijacking attacks when serving untrusted clients.
If JSON encoding fails or writing to the response fails, an HTTP error is returned.
func (*Context) SendStatus ¶
SendStatus sets the HTTP status code in the response without writing any body.
func (*Context) SendString ¶
SendString sends a plain text response with the given string content.
It writes directly to the response writer and returns any write error.
func (*Context) SendXML ¶
SendXML encodes v as XML and writes it to the response body. Returns an error if encoding fails.
func (*Context) SetContentType ¶
SetContentType sets the "Content-Type" header on the response. This defines the media type of the response body.
Example:
c.SetContentType("application/json")
c.SetContentType("text/html; charset=utf-8")
Parameters:
- ct: The content type string (e.g., "application/json").
func (*Context) SetCookie ¶
SetCookie sets a cookie in the HTTP response.
Parameters:
- cookie: pointer to a Cookie struct containing all cookie attributes (Name, Value, Path, Domain, MaxAge, Secure, HttpOnly, etc.)
Example:
c.SetCookie(&nexora.Cookie{
Name: "session_id",
Value: "abc123",
Path: "/",
MaxAge: 3600,
HttpOnly: true,
})
type DecoderFunc ¶
DecoderFunc is a function that decodes a byte slice into a Go value. It is used for decoding JSON and XML payloads.
type EncoderFunc ¶
EncoderFunc is a function that encodes a Go value into a byte slice. It is used for encoding JSON and XML payloads.
type HTTPError ¶
type HTTPError struct {
StatusCode int // HTTP status code (e.g. 404, 500)
Message string // Human-readable message
}
HTTPError represents an HTTP error with a status code and message.
func NewHTTPError ¶
NewHTTPError creates a new HTTPError.
type Handler ¶
Handler defines the signature for a request handler function that processes a Context and returns an error.
type IndentationEncoder ¶
IndentationEncoder is a function that encodes a Go value into an indented byte slice. It is used for encoding indented JSON and XML payloads.
type LoggerConfig ¶
type LoggerConfig struct {
Production bool // Enable json console output
Level zerolog.Level // Minimum log level
TimeFormat string // Time format for logs
Output io.Writer // Where logs are written (default: os.Stdout)
WithCaller bool // Include caller info (file:line)
ServiceName string // Optional service or app name
}
LoggerConfig holds Nexora's logger configuration
type Nexora ¶
type Nexora struct {
RouteGroup // Default route group for new routes
// contains filtered or unexported fields
}
Nexora is the main router object. All fields are private. Configurable via Config struct.
func New ¶
New creates a new instance of Nexora using the provided config. If a field is not set in the config, a default value will be applied.
func (*Nexora) Handle ¶
Handle registers a handler for a specific HTTP method and path. It is used under Get, Post, Put, Patch, Delete, Connect, Options, Trace and Wild methods. If the path contains optional parameters, it will register all possible paths. It panics if the method is empty or no handlers are provided. The path must start with a '/' character. If the path is invalid, it panics with an error message.
func (*Nexora) Route ¶
Route returns the named route. Nil is returned if the named route cannot be found.
func (*Nexora) Run ¶
Run starts the HTTP server on the specified address. It uses the ServeHTTP method to handle incoming requests. The address should be in the format "host:port", e.g., ":8080" or "localhost:8080". It returns an error if the server fails to start. Example usage: nexora.Run(":8080") If the address is empty, it defaults to ":8080".
type ResponseWriter ¶
type ResponseWriter struct {
http.ResponseWriter // underlying http.ResponseWriter
// contains filtered or unexported fields
}
ResponseWriter is a wrapper around http.ResponseWriter that captures the status code and response size for logging and middleware.
func NewResponseWriter ¶
func NewResponseWriter(w http.ResponseWriter) *ResponseWriter
NewResponseWriter creates a new wrapped ResponseWriter. It sets the default status code to 200.
func (*ResponseWriter) Size ¶
func (r *ResponseWriter) Size() int
Size returns the total number of bytes written to the response body.
func (*ResponseWriter) Status ¶
func (r *ResponseWriter) Status() int
Status returns the HTTP status code of the response.
func (*ResponseWriter) Write ¶
func (r *ResponseWriter) Write(b []byte) (int, error)
Write writes the response body and automatically sets the status code to 200 if WriteHeader was not previously called.
func (*ResponseWriter) WriteHeader ¶
func (r *ResponseWriter) WriteHeader(status int)
WriteHeader sets the HTTP status code for the response. If called multiple times with different codes, a warning is logged.
type Route ¶
type Route struct {
// contains filtered or unexported fields
}
Route represents a single route in the routing tree.
func (*Route) Name ¶
Name sets the name of the route. It also registers the route in the namedRoutes map of the Nexora instance.
func (*Route) URL ¶
URL creates a URL using the current route and the given parameters. The parameters should be given in the sequence of name1, value1, name2, value2, and so on. If a parameter in the route is not provided a value, the parameter token will remain in the resulting URL. The method will perform URL encoding for all given parameter values.
type RouteGroup ¶
type RouteGroup struct {
// contains filtered or unexported fields
}
RouteGroup represents a group of routes that share a common prefix and handlers.
func (*RouteGroup) Connect ¶
func (g *RouteGroup) Connect(path string, handler ...Handler) *Route
Connect registers a new CONNECT route with the specified path and handlers.
func (*RouteGroup) Delete ¶
func (g *RouteGroup) Delete(path string, handler ...Handler) *Route
Delete registers a new DELETE route with the specified path and handlers.
func (*RouteGroup) Get ¶
func (g *RouteGroup) Get(path string, handler ...Handler) *Route
Get registers a new GET route with the specified path and handlers.
func (*RouteGroup) Group ¶
func (g *RouteGroup) Group(prefix string, handlers ...Handler) *RouteGroup
Group creates a RouteGroup with the given route path prefix and handlers. The new group will combine the existing path prefix with the new one. If no handler is provided, the new group will inherit the handlers registered with the current group.
func (*RouteGroup) Head ¶
func (g *RouteGroup) Head(path string, handler ...Handler) *Route
Head registers a new HEAD route with the specified path and handlers.
func (*RouteGroup) Options ¶
func (g *RouteGroup) Options(path string, handler ...Handler) *Route
Options registers a new OPTIONS route with the specified path and handlers.
func (*RouteGroup) Patch ¶
func (g *RouteGroup) Patch(path string, handler ...Handler) *Route
Patch registers a new PATCH route with the specified path and handlers.
func (*RouteGroup) Post ¶
func (g *RouteGroup) Post(path string, handler ...Handler) *Route
Post registers a new POST route with the specified path and handlers.
func (*RouteGroup) Put ¶
func (g *RouteGroup) Put(path string, handler ...Handler) *Route
Put registers a new PUT route with the specified path and handlers.
func (*RouteGroup) Trace ¶
func (g *RouteGroup) Trace(path string, handler ...Handler) *Route
Trace registers a new TRACE route with the specified path and handlers.
func (*RouteGroup) Use ¶
func (g *RouteGroup) Use(handlers ...Handler)