Documentation
¶
Index ¶
- Constants
- Variables
- func NewError(message string) error
- func ReleaseContext(ctx *Ctx)
- func ReleaseResponseWriter(w ResponseWriter)
- func StatusText(statusCode int) string
- type Config
- type Cookie
- type Ctx
- func (c *Ctx) BindForm(obj interface{}) error
- func (c *Ctx) BindJSON(obj interface{}) error
- func (c *Ctx) ClearCookies() *Ctx
- func (c *Ctx) Cookie(cookie *Cookie) *Ctx
- func (c *Ctx) Cookies(name string) string
- func (c *Ctx) Data(contentType string, data []byte)
- func (c *Ctx) Error(err error) *Ctx
- func (c *Ctx) Get(key string) string
- func (c *Ctx) GetError() error
- func (c *Ctx) GetParam(key string) string
- func (c *Ctx) HTML(html string)
- func (c *Ctx) Header() *Header
- func (c *Ctx) Host() string
- func (c *Ctx) IP() string
- func (c *Ctx) JSON(obj interface{})
- func (c *Ctx) Method() string
- func (c *Ctx) Next()
- func (c *Ctx) Param(key string) string
- func (c *Ctx) ParseJSON(jsonStr string) (*fastjson.Value, error)
- func (c *Ctx) ParseJSONBody() (*fastjson.Value, error)
- func (c *Ctx) Path() string
- func (c *Ctx) Protocol() string
- func (c *Ctx) Query(key string) string
- func (c *Ctx) QueryArray(key string) []string
- func (c *Ctx) Referer() string
- func (c *Ctx) RemoteAddr() string
- func (c *Ctx) Set(key, value string) *Ctx
- func (c *Ctx) Status(code int) *Ctx
- func (c *Ctx) StatusCode() int
- func (c *Ctx) String(format string, values ...interface{})
- func (c *Ctx) UserAgent() string
- func (c *Ctx) UserData(key string, value ...interface{}) interface{}
- type Group
- func (g *Group) CONNECT(pattern string, handlers ...Handler) *Group
- func (g *Group) DELETE(pattern string, handlers ...Handler) *Group
- func (g *Group) GET(pattern string, handlers ...Handler) *Group
- func (g *Group) Group(prefix string) *Group
- func (g *Group) HEAD(pattern string, handlers ...Handler) *Group
- func (g *Group) Handle(pattern, method string, handlers ...Handler) *Group
- func (g *Group) OPTIONS(pattern string, handlers ...Handler) *Group
- func (g *Group) PATCH(pattern string, handlers ...Handler) *Group
- func (g *Group) POST(pattern string, handlers ...Handler) *Group
- func (g *Group) PUT(pattern string, handlers ...Handler) *Group
- func (g *Group) TRACE(pattern string, handlers ...Handler) *Group
- func (g *Group) Use(middleware ...interface{}) *Group
- type Handler
- type Header
- func (h Header) Add(key, value string)
- func (h Header) Clone() Header
- func (h Header) Del(key string)
- func (h Header) Get(key string) string
- func (h Header) Set(key, value string)
- func (h Header) Values(key string) []string
- func (h Header) Write(w stringWriter) error
- func (h Header) WriteSubset(w stringWriter, exclude map[string]bool) error
- type HttpError
- type Middleware
- type MiddlewareFunc
- type Params
- type Request
- type ResponseWriter
- type Router
- func (r *Router) CONNECT(pattern string, handlers ...Handler) *Router
- func (r *Router) DELETE(pattern string, handlers ...Handler) *Router
- func (r *Router) GET(pattern string, handlers ...Handler) *Router
- func (r *Router) Group(prefix string) *Group
- func (r *Router) HEAD(pattern string, handlers ...Handler) *Router
- func (r *Router) Handle(pattern, method string, handlers ...Handler) *Router
- func (r *Router) HandleStatic(prefix, root string, config ...Static) *Router
- func (r *Router) OPTIONS(pattern string, handlers ...Handler) *Router
- func (r *Router) PATCH(pattern string, handlers ...Handler) *Router
- func (r *Router) POST(pattern string, handlers ...Handler) *Router
- func (r *Router) PUT(pattern string, handlers ...Handler) *Router
- func (r *Router) STATIC(prefix, root string, config ...Static) *Router
- func (r *Router) ServeHTTP(ctx *Ctx, req *Request)
- func (r *Router) TRACE(pattern string, handlers ...Handler) *Router
- func (r *Router) Use(middleware ...interface{})
- type Server
- func (s *Server) CONNECT(pattern string, handlers ...Handler) *Router
- func (s *Server) DELETE(pattern string, handlers ...Handler) *Router
- func (s *Server) GET(pattern string, handlers ...Handler) *Router
- func (s *Server) Group(prefix string) *Group
- func (s *Server) HEAD(pattern string, handlers ...Handler) *Router
- func (s *Server) Listen(addr string) error
- func (s *Server) NotFound(handler Handler)
- func (s *Server) OPTIONS(pattern string, handlers ...Handler) *Router
- func (s *Server) PATCH(pattern string, handlers ...Handler) *Router
- func (s *Server) POST(pattern string, handlers ...Handler) *Router
- func (s *Server) PUT(pattern string, handlers ...Handler) *Router
- func (s *Server) Router() *Router
- func (s *Server) STATIC(prefix, root string, config ...Static) *Router
- func (s *Server) Shutdown(ctx context.Context) error
- func (s *Server) TRACE(pattern string, handlers ...Handler) *Router
- func (s *Server) Use(middleware ...interface{})
- type Static
- type Storage
- type StorageError
Constants ¶
const ( MethodGet = "GET" MethodHead = "HEAD" MethodPost = "POST" MethodPut = "PUT" MethodPatch = "PATCH" MethodDelete = "DELETE" MethodConnect = "CONNECT" MethodOptions = "OPTIONS" MethodTrace = "TRACE" )
HTTP methods as registered with IANA. See: https://www.iana.org/assignments/http-methods/http-methods.xhtml
const ( MIMETextXML = "text/xml" MIMETextHTML = "text/html" MIMETextPlain = "text/plain" MIMETextJavaScript = "text/javascript" MIMETextCSS = "text/css" MIMEApplicationXML = "application/xml" MIMEApplicationJSON = "application/json" MIMEApplicationCBOR = "application/cbor" MIMEApplicationForm = "application/x-www-form-urlencoded" MIMEOctetStream = "application/octet-stream" MIMEMultipartForm = "multipart/form-data" MIMEApplicationJavaScript = "application/javascript" MIMETextXMLCharsetUTF8 = "text/xml; charset=utf-8" MIMETextHTMLCharsetUTF8 = "text/html; charset=utf-8" MIMETextPlainCharsetUTF8 = "text/plain; charset=utf-8" MIMETextJavaScriptCharsetUTF8 = "text/javascript; charset=utf-8" MIMETextCSSCharsetUTF8 = "text/css; charset=utf-8" MIMEApplicationXMLCharsetUTF8 = "application/xml; charset=utf-8" MIMEApplicationJSONCharsetUTF8 = "application/json; charset=utf-8" MIMEApplicationJavaScriptCharsetUTF8 = "application/javascript; charset=utf-8" )
MIME types that are commonly used
const ( // Authentication. HeaderAuthorization = "Authorization" HeaderProxyAuthenticate = "Proxy-Authenticate" HeaderProxyAuthorization = "Proxy-Authorization" HeaderWWWAuthenticate = "WWW-Authenticate" // Caching. HeaderAge = "Age" HeaderCacheControl = "Cache-Control" HeaderClearSiteData = "Clear-Site-Data" HeaderExpires = "Expires" HeaderPragma = "Pragma" HeaderWarning = "Warning" // Client hints. HeaderAcceptCH = "Accept-CH" HeaderAcceptCHLifetime = "Accept-CH-Lifetime" HeaderContentDPR = "Content-DPR" HeaderDPR = "DPR" HeaderEarlyData = "Early-Data" HeaderSaveData = "Save-Data" HeaderViewportWidth = "Viewport-Width" HeaderWidth = "Width" // Conditionals. HeaderETag = "ETag" HeaderIfMatch = "If-Match" HeaderIfModifiedSince = "If-Modified-Since" HeaderIfNoneMatch = "If-None-Match" HeaderIfUnmodifiedSince = "If-Unmodified-Since" HeaderLastModified = "Last-Modified" HeaderVary = "Vary" // Connection management. HeaderConnection = "Connection" HeaderKeepAlive = "Keep-Alive" HeaderProxyConnection = "Proxy-Connection" // Content negotiation. HeaderAccept = "Accept" HeaderAcceptCharset = "Accept-Charset" HeaderAcceptEncoding = "Accept-Encoding" HeaderAcceptLanguage = "Accept-Language" // Controls. HeaderCookie = "Cookie" HeaderExpect = "Expect" HeaderMaxForwards = "Max-Forwards" HeaderSetCookie = "Set-Cookie" // CORS. 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" // Do Not Track. HeaderDNT = "DNT" HeaderTk = "Tk" // Downloads. HeaderContentDisposition = "Content-Disposition" // Message body information. HeaderContentEncoding = "Content-Encoding" HeaderContentLanguage = "Content-Language" HeaderContentLength = "Content-Length" HeaderContentLocation = "Content-Location" HeaderContentType = "Content-Type" // Proxies. HeaderForwarded = "Forwarded" HeaderVia = "Via" HeaderXForwardedFor = "X-Forwarded-For" HeaderXForwardedHost = "X-Forwarded-Host" HeaderXForwardedProto = "X-Forwarded-Proto" // Redirects. HeaderLocation = "Location" // Request context. HeaderFrom = "From" HeaderHost = "Host" HeaderReferer = "Referer" HeaderReferrerPolicy = "Referrer-Policy" HeaderUserAgent = "User-Agent" // Response context. HeaderAllow = "Allow" HeaderServer = "Server" // Range requests. HeaderAcceptRanges = "Accept-Ranges" HeaderContentRange = "Content-Range" HeaderIfRange = "If-Range" HeaderRange = "Range" // Security. 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" // Server-sent event. HeaderLastEventID = "Last-Event-ID" HeaderNEL = "NEL" HeaderPingFrom = "Ping-From" HeaderPingTo = "Ping-To" HeaderReportTo = "Report-To" // Transfer coding. HeaderTE = "TE" HeaderTrailer = "Trailer" HeaderTransferEncoding = "Transfer-Encoding" // WebSockets. HeaderSecWebSocketAccept = "Sec-WebSocket-Accept" HeaderSecWebSocketExtensions = "Sec-WebSocket-Extensions" // #nosec G101 HeaderSecWebSocketKey = "Sec-WebSocket-Key" HeaderSecWebSocketProtocol = "Sec-WebSocket-Protocol" HeaderSecWebSocketVersion = "Sec-WebSocket-Version" // Other. 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" HeaderXRequestedWith = "X-Requested-With" HeaderXRobotsTag = "X-Robots-Tag" HeaderXUACompatible = "X-UA-Compatible" )
Headers were borrowed from valyala/fasthttp
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 StatusNonAuthoritativeInfo = 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 as registered with IANA. See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
Variables ¶
var DefaultStaticConfig = Static{ Compress: false, ByteRange: false, Browse: false, Download: false, Index: "index.html", CacheDuration: 10 * time.Second, MaxAge: 0, InMemoryCache: true, MaxCacheSize: 100 * 1024 * 1024, MaxCacheItems: 1000, ModifyResponse: nil, }
DefaultStaticConfig is the default static configuration.
var ErrNotFound = NewError("key not found")
ErrNotFound is returned when a key is not found in the storage.
Functions ¶
func ReleaseContext ¶
func ReleaseContext(ctx *Ctx)
ReleaseContext returns a Ctx to the pool after resetting its state. This function should be called when you're done with a context to allow reuse. It clears all fields and returns the Ctx to the pool.
Parameters:
- ctx: The context to reset and return to the pool
Note: After calling this function, the ctx should not be used anymore.
func ReleaseResponseWriter ¶
func ReleaseResponseWriter(w ResponseWriter)
ReleaseResponseWriter returns a ResponseWriter to the pool
func StatusText ¶
StatusText returns a text for the given HTTP status code. If the code is unknown, "Unknown Status Code" is returned.
Types ¶
type Config ¶
type Config struct {
// ReadTimeout is the maximum duration for reading the entire request, including the body.
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 when keep-alives are enabled.
IdleTimeout time.Duration
// DisableStartupMessage determines whether to print the startup message when the server starts.
DisableStartupMessage bool
// ErrorHandler is called when an error occurs during request processing.
ErrorHandler Handler
}
Config represents server configuration options.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns a default server configuration with pre-configured timeouts and other settings suitable for most applications. The default configuration includes: - ReadTimeout: 5 seconds - WriteTimeout: 10 seconds - IdleTimeout: 15 seconds - DisableStartupMessage: false - ErrorHandler: default error handler
type Cookie ¶
type Cookie struct {
Name string `json:"name"` // The name of the cookie
Value string `json:"value"` // The value of the cookie
Path string `json:"path"` // Specifies a URL path which is allowed to receive the cookie
Domain string `json:"domain"` // Specifies the domain which is allowed to receive the cookie
MaxAge int `json:"max_age"` // The maximum age (in seconds) of the cookie
Expires time.Time `json:"expires"` // The expiration date of the cookie
Secure bool `json:"secure"` // Indicates that the cookie should only be transmitted over a secure HTTPS connection
HTTPOnly bool `json:"http_only"` // Indicates that the cookie is accessible only through the HTTP protocol
SameSite string `json:"same_site"` // Controls whether or not a cookie is sent with cross-site requests
Partitioned bool `json:"partitioned"` // Indicates if the cookie is stored in a partitioned cookie jar
SessionOnly bool `json:"session_only"` // Indicates if the cookie is a session-only cookie
}
Cookie represents an HTTP cookie as sent in the Set-Cookie header of an HTTP response.
type Ctx ¶
type Ctx struct {
Writer ResponseWriter
Request *Request
// contains filtered or unexported fields
}
Ctx represents the context of an HTTP request. It contains the request and response data, as well as utilities for handling the request and generating a response. It also manages middleware execution.
func GetContext ¶
func GetContext(w http.ResponseWriter, r *http.Request) *Ctx
GetContext gets a Ctx from the pool and initializes it with the given writer and request. This function reuses Ctx objects from a pool to reduce memory allocations.
Parameters:
- w: The http.ResponseWriter to use for the response
- r: The http.Request to process
Returns:
- A properly initialized *Ctx object ready for request processing
func (*Ctx) BindForm ¶
BindForm parses form data from the request and binds it to the provided object. It supports the following Content-Types: - application/x-www-form-urlencoded - multipart/form-data - text/plain (treated as URL-encoded) - empty Content-Type (treated as URL-encoded) The struct fields should be tagged with `form:"field_name"` to specify the form field name. If a field doesn't have a form tag, it will be skipped. Parameters:
- obj: The object to bind the form data to
Returns:
- An error if parsing the form data fails or if the provided object is not a pointer to a struct
- nil if successful
Example usage in a route handler:
func MyHandler(c *ngebut.Ctx) {
var data MyDataType
if err := c.BindForm(&data); err != nil {
c.Error(err)
return
}
// Now data is populated with the form data from the request
c.JSON(data)
}
func (*Ctx) BindJSON ¶
BindJSON unmarshals the JSON data from the request body into the provided object. It reads the request body, decodes the JSON, and populates the object. If the request body is nil or if unmarshaling fails, it returns an error. This method is typically used in route handlers to bind incoming JSON data to a struct. Parameters:
- obj: The object to unmarshal the JSON data into
Returns:
- An error if the request body is nil or if unmarshaling fails
- nil if successful
Example usage in a route handler:
func MyHandler(c *ngebut.Ctx) {
var data MyDataType
if err := c.BindJSON(&data); err != nil {
c.Error(err)
return
}
// Now data is populated with the JSON from the request body
c.JSON(data)
}
func (*Ctx) ClearCookies ¶
ClearCookies removes all cookies for the context by setting an empty Set-Cookie header.
func (*Ctx) Cookie ¶
Cookie sets a cookie in the response. It adds the Set-Cookie header to the response with the serialized cookie.
func (*Ctx) Cookies ¶
Cookies retrieve a cookie from the request by its name. It returns the cookie value as a string, or an empty string if the cookie is not found.
func (*Ctx) Data ¶
Data sends a raw byte slice response with the specified content type. This is useful for sending binary data like images, PDFs, etc.
Parameters:
- contentType: The MIME type of the data (e.g., "image/jpeg", "application/pdf")
- data: The byte slice containing the data to send
Note: This method writes the response immediately and sets the status code.
func (*Ctx) Error ¶
Error sets an error in the context. This can be used to store errors that occur during request processing. If the current status code is less than 400, it will be set to 500 (Internal Server Error).
Parameters:
- err: The error to store in the context
Returns:
- The context itself for method chaining
func (*Ctx) Get ¶
Get retrieves a response header value by its key.
Parameters:
- key: The header name to retrieve
Returns:
- The header value as a string, or empty string if not found
func (*Ctx) GetError ¶
GetError returns the error stored in the context. If no explicit error was set but the status code is 400 or higher, it returns a new error with the status text as the message.
Returns:
- The error stored in the context, a new error based on the status code, or nil if no error condition exists
func (*Ctx) HTML ¶
HTML sends an HTML response with the provided content. It sets the Content-Type header to "text/html; charset=utf-8".
Parameters:
- html: The HTML content to send as a response
Note: This method writes the response immediately and sets the status code.
func (*Ctx) Header ¶
Header returns the header map that will be sent with the response. This can be used to access the current headers or to modify them.
Returns:
- The Header object containing all response headers
func (*Ctx) IP ¶
IP returns the client's IP address. It tries to determine the real IP address by checking various headers that might be set by proxies, before falling back to the direct connection IP.
The order of precedence is: 1. X-Forwarded-For header (first value) 2. X-Real-Ip header 3. RemoteAddr from the request
Returns:
- The client's IP address as a string, or empty string if not determinable
func (*Ctx) JSON ¶
func (c *Ctx) JSON(obj interface{})
JSON sends a JSON response by encoding the provided object. It sets the Content-Type header to "application/json; charset=utf-8".
Parameters:
- obj: The object to be encoded to JSON
Note: This method writes the response immediately and sets the status code.
func (*Ctx) Method ¶
Method returns the HTTP method of the request (e.g., GET, POST, PUT). If the request is nil, it returns an empty string. This method is useful for determining how the request was made.
func (*Ctx) Next ¶
func (c *Ctx) Next()
Next calls the next middleware or handler in the stack. If there are no more middleware functions, it calls the final handler. This method is typically called within middleware to pass control to the next middleware or to the final route handler.
Example usage in middleware:
func MyMiddleware(c *ngebut.Ctx) {
// Do something before the next middleware or handler
c.Next()
// Do something after the next middleware or handler has completed
}
func (*Ctx) Param ¶
Param retrieves a URL path parameter value by its key. For example, in a route "/users/:id", Param("id") would return the value in the URL path.
Parameters:
- key: The parameter name to retrieve
Returns:
- The parameter value as a string, or empty string if not found
func (*Ctx) ParseJSON ¶
ParseJSON parses a JSON string using fastjson and returns the parsed value. It uses a pool of parsers for better performance.
Parameters:
- jsonStr: The JSON string to parse
Returns:
- The parsed JSON value, or nil if there was an error
- Any error that occurred during parsing
func (*Ctx) ParseJSONBody ¶
ParseJSONBody parses the request body as JSON using fastjson. It uses a pool of parsers for better performance.
Returns:
- The parsed JSON value, or nil if there was an error
- Any error that occurred during parsing
func (*Ctx) Path ¶
Path returns the URL path of the request. If the request is nil, it returns an empty string. This method is useful for determining the requested resource. For example, for a request to "/users/123", it would return "/users/123". If the request is nil, it returns an empty string.
func (*Ctx) Protocol ¶
Protocol retrieves the protocol scheme (e.g., "http" or "https") from the request. It first checks proxy headers like X-Forwarded-Proto, then falls back to URL.Scheme, and finally determines based on TLS connection status. Returns "http" as default if the protocol cannot be determined.
func (*Ctx) Query ¶
Query retrieves a URL query parameter value by its key. For example, in a URL "?name=john", Query("name") would return "john".
Parameters:
- key: The query parameter name to retrieve
Returns:
- The query parameter value as a string, or empty string if not found
func (*Ctx) QueryArray ¶
QueryArray retrieves all values for a URL query parameter by its key. For example, in a URL "?color=red&color=blue", QueryArray("color") would return ["red", "blue"].
Parameters:
- key: The query parameter name to retrieve
Returns:
- A slice of strings containing all values for the parameter, or an empty slice if not found
func (*Ctx) Referer ¶
Referer retrieves the "Referer" header value from the incoming HTTP request. Returns an empty string if the request is nil or the header is absent.
func (*Ctx) RemoteAddr ¶
RemoteAddr returns the direct remote address of the request. Unlike IP(), this method only looks at the RemoteAddr field of the request and doesn't check any headers.
Returns:
- The remote IP address as a string, or empty string if not available
func (*Ctx) Set ¶
Set sets a response header with the given key and value. It sets the header in both c.header and c.Writer.Header() to ensure it's included in the response even if set after c.Next() in middleware.
Parameters:
- key: The header name
- value: The header value
Returns:
- The context itself for method chaining
func (*Ctx) Status ¶
Status sets the HTTP status code for the response.
Parameters:
- code: The HTTP status code to set (e.g., 200, 404, 500)
Returns:
- The context itself for method chaining
func (*Ctx) StatusCode ¶
StatusCode returns the current HTTP status code set for the response.
Returns:
- The HTTP status code as an integer
func (*Ctx) String ¶
String sends a plain text response with the given format and values. It sets the Content-Type header to "text/plain; charset=utf-8". If values are provided, it formats the string using fmt.Sprintf.
Parameters:
- format: The string format (can contain format specifiers if values are provided)
- values: Optional values to be formatted into the string
Note: This method writes the response immediately and sets the status code.
type Group ¶
type Group struct {
// contains filtered or unexported fields
}
Group represents a group of routes with a common prefix and middleware.
type Handler ¶
type Handler func(c *Ctx)
Handler is a function that handles an HTTP request with a Ctx. This is the same signature as middleware functions, making them interchangeable.
func CompileMiddleware ¶
func CompileMiddleware(handler Handler, middleware ...Middleware) Handler
CompileMiddleware precomposes multiple middleware functions into a single handler function. This eliminates the need for runtime middleware chaining, reducing allocations and function call overhead. The middleware functions are executed in the order they are provided.
Unlike the dynamic middleware approach that uses c.Next(), this function creates a static chain where each middleware is directly called in sequence, eliminating the overhead of dynamic dispatch.
Note: This approach is most effective for middleware that doesn't rely on c.Next() for complex behavior like executing code after the next middleware completes.
type Header ¶
Header represents the key-value pairs in an HTTP header. The keys should be in canonical form, as returned by textproto.CanonicalMIMEHeaderKey.
func NewHeader ¶
func NewHeader() *Header
NewHeader creates a new empty Header with pre-allocated capacity.
func NewHeaderFromMap ¶
NewHeaderFromMap creates a new Header from a map[string][]string. This optimized version avoids unnecessary copying of values when possible.
func UpdateHeaderFromMap ¶
UpdateHeaderFromMap updates an existing Header with values from a map[string][]string. This function avoids allocating a new Header map, reducing memory allocations. It returns the updated Header.
func (Header) Add ¶
Add adds the key, value pair to the header. It appends to any existing values associated with key. The key is case insensitive; it is canonicalized by textproto.CanonicalMIMEHeaderKey. This optimized version reduces allocations by appending directly when possible.
func (Header) Del ¶
Del deletes the values associated with key. The key is case insensitive; it is canonicalized by textproto.CanonicalMIMEHeaderKey.
func (Header) Get ¶
Get gets the first value associated with the given key. If there are no values associated with the key, Get returns "". It is case insensitive; textproto.CanonicalMIMEHeaderKey is used to canonicalize the provided key. To use non-canonical keys, access the map directly.
func (Header) Set ¶
Set sets the header entries associated with key to the single element value. It replaces any existing values associated with key. The key is case insensitive; it is canonicalized by textproto.CanonicalMIMEHeaderKey. To use non-canonical keys, assign to the map directly.
func (Header) Values ¶
Values returns all values associated with the given key. It is case insensitive; textproto.CanonicalMIMEHeaderKey is used to canonicalize the provided key. To use non-canonical keys, access the map directly. The returned slice is a copy to avoid concurrent modification issues. This optimized version avoids unnecessary copying for single-value headers.
type HttpError ¶
type HttpError struct {
Code int // HTTP status code
Message string // Error message
Err error // Original error, if any
}
HttpError represents an HTTP error with a status code and message.
func NewHttpError ¶
NewHttpError creates a new HttpError with the given status code and message.
func NewHttpErrorWithError ¶
NewHttpErrorWithError creates a new HttpError with the given status code, message, and error.
type Middleware ¶
type Middleware func(c *Ctx)
Middleware is a function that can be used as middleware. It has the same signature as Handler, making them interchangeable. The function should call c.Next() to continue to the next middleware or handler.
type MiddlewareFunc ¶
type MiddlewareFunc = Middleware
MiddlewareFunc is an alias for Middleware for backward compatibility. It's similar to the middleware pattern used in gofiber.
type Params ¶
type Params struct {
// contains filtered or unexported fields
}
Params is a fixed-size struct for URL parameters to avoid allocations
type Request ¶
type Request struct {
// Method specifies the HTTP method (GET, POST, PUT, etc.).
Method string
// URL specifies the URL being requested.
URL *url.URL
// Proto is the protocol version.
Proto string
// Header contains the request header fields.
Header *Header
// Body is the request's body.
Body []byte
// ContentLength records the length of the associated content.
ContentLength int64
// Host specifies the host on which the URL is sought.
Host string
// RemoteAddr allows HTTP servers and other software to record
// the network address that sent the request.
RemoteAddr string
// RequestURI is the unmodified request-target as sent by the client
// to a server.
RequestURI string
// contains filtered or unexported fields
}
Request represents an HTTP request.
func NewRequest ¶
NewRequest creates a new Request from an http.Request. It uses the requestPool to reuse Request objects when possible.
func (*Request) SetContext ¶
type ResponseWriter ¶
type ResponseWriter interface {
// Header returns the header map that will be sent by WriteHeader.
// The Header map also is the mechanism with which
// Handlers can set HTTP trailers.
Header() *Header
// Write writes the data to the connection as part of an HTTP reply.
Write([]byte) (int, error)
// WriteHeader sends an HTTP response header with the provided
// status code.
WriteHeader(statusCode int)
// Flush writes the buffered response to the underlying writer.
Flush()
}
ResponseWriter is the interface used by an HTTP handler to construct an HTTP response.
func NewResponseWriter ¶
func NewResponseWriter(w http.ResponseWriter) ResponseWriter
NewResponseWriter creates a new ResponseWriter from an http.ResponseWriter
type Router ¶
type Router struct {
Routes []route
NotFound Handler
// contains filtered or unexported fields
}
Router is an HTTP request router.
func (*Router) HandleStatic ¶
HandleStatic registers a new route for serving static files.
func (*Router) ServeHTTP ¶
ServeHTTP implements a modified http.Handler interface that accepts a Ctx.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server represents an HTTP server.
func New ¶
New creates a new server with the given configuration. This is the main entry point for creating a ngebut server instance.
Parameters:
- config: The server configuration (use DefaultConfig() for sensible defaults)
Returns:
- A new Server instance ready to be configured with routes and middleware
type Static ¶
type Static struct {
// When set to true, the server tries minimizing CPU usage by caching compressed files.
// Optional. Default value false
Compress bool `json:"compress"`
// When set to true, enables byte range requests.
// Optional. Default value false
ByteRange bool `json:"byte_range"`
// When set to true, enables directory browsing.
// Optional. Default value false.
Browse bool `json:"browse"`
// When set to true, enables direct download.
// Optional. Default value false.
Download bool `json:"download"`
// The name of the index file for serving a directory.
// Optional. Default value "index.html".
Index string `json:"index"`
// Expiration duration for inactive file handlers.
// Use a negative time.Duration to disable it.
//
// Optional. Default value 10 * time.Second.
CacheDuration time.Duration `json:"cache_duration"`
// The value for the Cache-Control HTTP-header
// that is set on the file response. MaxAge is defined in seconds.
//
// Optional. Default value 0.
MaxAge int `json:"max_age"`
// When set to true, enables in-memory caching of file contents.
// This can significantly improve performance for frequently accessed files.
// Optional. Default value false.
InMemoryCache bool `json:"in_memory_cache"`
// Maximum size of the in-memory cache in bytes.
// Optional. Default value 100MB.
MaxCacheSize int64 `json:"max_cache_size"`
// Maximum number of files to store in the in-memory cache.
// Optional. Default value 1000.
MaxCacheItems int `json:"max_cache_items"`
// ModifyResponse defines a function that allows you to alter the response.
//
// Optional. Default: nil
ModifyResponse Handler
// Next defines a function to skip this middleware when returned true.
//
// Optional. Default: nil
Next func(c *Ctx) bool
}
Static defines configuration options when defining static assets.
type Storage ¶
type Storage interface {
// Get retrieves a value for the given key.
// Returns ErrNotFound if the key doesn't exist.
Get(ctx context.Context, key string) ([]byte, error)
// Set stores a value for the given key.
// If ttl is positive, the key will expire after the specified duration.
// If ttl is zero or negative, the key will not expire.
Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
// Delete removes a key from the storage.
// It's not an error to delete a non-existent key.
Delete(ctx context.Context, key string) error
// Clear removes all keys from the storage.
Clear(ctx context.Context) error
// Has checks if a key exists in the storage.
Has(ctx context.Context, key string) (bool, error)
}
Storage defines the interface for storage implementations. This interface can be used for various storage needs including session management.
type StorageError ¶
type StorageError struct {
// contains filtered or unexported fields
}
StorageError represents a storage error.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
static
command
|
|
|
internal
|
|
|
httpparser
Package httpparser provides HTTP parsing functionality for the ngebut framework.
|
Package httpparser provides HTTP parsing functionality for the ngebut framework. |
|
middleware
|
|