ngebut

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jul 5, 2025 License: MIT Imports: 30 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README ΒΆ

GitHub release Go Dev License Go Report Card Unit Tests

Ngebut is a web framework for Go designed for speed and efficiency.
Built on top of gnet, a high-performance non-blocking networking library for Go.

⚠️ Maintenance Notice: Ngebut is currently under active development and maintenance. Some APIs may change before the first stable release.

πŸ“š Documentation

For more detailed documentation, please visit the Go Package Documentation.

πŸ—οΈ Architecture

graph TD
    A[Client Request] --> B[Ngebut Server]
    B --> C{Router}
    C --> D[Middleware Chain]
    D --> E[Route Handler]
    E --> F[Context Processing]
    F --> G[Response Generation]
    G --> H[Client]

    subgraph "Ngebut Framework"
        B[Ngebut Server<br>gnet-based]
        C
        D
        E
        F
        G
    end

πŸ’‘ Inspiration: Ngebut is inspired by GoFiber and Hertz Framework, aiming to provide a similar developer experience while leveraging gnet for networking.

⚑️ Quick Start

# Install the framework
go get github.com/ryanbekhen/ngebut

✨ Features

  • Efficient Performance: Built on gnet, a high-performance non-blocking networking library for Go
  • Simple API: Intuitive and easy-to-use API for rapid development
  • Flexible Routing: Supports URL parameters and all standard HTTP methods (GET, POST, PUT, DELETE, etc.)
  • Middleware Support: Built-in middleware for access logging and session management
  • Group Routing: Organize routes with groups that share common prefixes and middleware
  • Context-Based Handling: Request and response handling through a powerful context object

πŸš€ Basic Example

For a quick start, check out this simple example:

package main

import (
	"github.com/ryanbekhen/ngebut"
)

func main() {
	server := ngebut.New(ngebut.DefaultConfig())

	server.GET("/", func(c *ngebut.Ctx) {
		c.String("Hello, World!")
	})

	server.Listen(":8080")
}

πŸ“– Documentation

For detailed documentation on server configuration, routing, middleware, and all other features, please refer to the Go Package Documentation.

πŸ“Š Benchmarks

For detailed benchmark information, please refer to the Benchmark Documentation.

For comparative benchmarks against other frameworks like Fiber and standard net/http, check out the benchmarks directory.

🀝 Contributing

Contributions are very welcome! Please submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“œ License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

View Source
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

View Source
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

View Source
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

View Source
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
	StatusUnauthorized                 = 401 // RFC 7235, 3.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
	StatusUnavailableForLegalReasons   = 451 // RFC 7725, 3

	StatusInternalServerError           = 500 // RFC 7231, 6.6.1
	StatusNotImplemented                = 501 // RFC 7231, 6.6.2
	StatusBadGateway                    = 502 // RFC 7231, 6.6.3
	StatusServiceUnavailable            = 503 // RFC 7231, 6.6.4
	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 ΒΆ

View Source
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.

View Source
var ErrNotFound = NewError("key not found")

ErrNotFound is returned when a key is not found in the storage.

Functions ΒΆ

func NewError ΒΆ

func NewError(message string) error

NewError creates a new error with the given message.

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 ΒΆ

func StatusText(statusCode int) string

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 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.

func (*Cookie) String ΒΆ

func (c *Cookie) String() string

String returns the serialized cookie as it would appear in the Set-Cookie header.

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 ΒΆ

func (c *Ctx) BindForm(obj interface{}) error

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 ΒΆ

func (c *Ctx) BindJSON(obj interface{}) error

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 ΒΆ

func (c *Ctx) ClearCookies() *Ctx

ClearCookies removes all cookies for the context by setting an empty Set-Cookie header.

func (*Ctx) Cookie ΒΆ

func (c *Ctx) Cookie(cookie *Cookie) *Ctx

Cookie sets a cookie in the response. It adds the Set-Cookie header to the response with the serialized cookie.

func (*Ctx) Cookies ΒΆ

func (c *Ctx) Cookies(name string) string

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 ΒΆ

func (c *Ctx) Data(contentType string, data []byte)

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 ΒΆ

func (c *Ctx) Error(err error) *Ctx

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 ΒΆ

func (c *Ctx) Get(key string) string

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 ΒΆ

func (c *Ctx) GetError() error

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) GetParam ΒΆ

func (c *Ctx) GetParam(key string) string

GetParam retrieves a URL parameter from the request context

func (*Ctx) HTML ΒΆ

func (c *Ctx) HTML(html string)

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 ΒΆ

func (c *Ctx) Header() *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) Host ΒΆ

func (c *Ctx) Host() string

Host returns the host of the request.

func (*Ctx) IP ΒΆ

func (c *Ctx) IP() string

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 ΒΆ

func (c *Ctx) Method() string

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 ΒΆ

func (c *Ctx) Param(key string) string

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 ΒΆ

func (c *Ctx) ParseJSON(jsonStr string) (*fastjson.Value, error)

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 ΒΆ

func (c *Ctx) ParseJSONBody() (*fastjson.Value, error)

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 ΒΆ

func (c *Ctx) Path() string

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 ΒΆ

func (c *Ctx) Protocol() string

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 ΒΆ

func (c *Ctx) Query(key string) string

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 ΒΆ

func (c *Ctx) QueryArray(key string) []string

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 ΒΆ

func (c *Ctx) Referer() string

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 ΒΆ

func (c *Ctx) RemoteAddr() string

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 ΒΆ

func (c *Ctx) Set(key, value string) *Ctx

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 ΒΆ

func (c *Ctx) Status(code int) *Ctx

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 ΒΆ

func (c *Ctx) StatusCode() int

StatusCode returns the current HTTP status code set for the response.

Returns:

  • The HTTP status code as an integer

func (*Ctx) String ΒΆ

func (c *Ctx) String(format string, values ...interface{})

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.

func (*Ctx) UserAgent ΒΆ

func (c *Ctx) UserAgent() string

UserAgent returns the value of the "User-Agent" header from the request, or an empty string if the request is nil.

func (*Ctx) UserData ΒΆ

func (c *Ctx) UserData(key string, value ...interface{}) interface{}

UserData sets or get user-specific data in the context.

type Group ΒΆ

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

Group represents a group of routes with a common prefix and middleware.

func (*Group) CONNECT ΒΆ

func (g *Group) CONNECT(pattern string, handlers ...Handler) *Group

CONNECT registers a new route with the CONNECT method.

func (*Group) DELETE ΒΆ

func (g *Group) DELETE(pattern string, handlers ...Handler) *Group

DELETE registers a new route with the DELETE method.

func (*Group) GET ΒΆ

func (g *Group) GET(pattern string, handlers ...Handler) *Group

GET registers a new route with the GET method.

func (*Group) Group ΒΆ

func (g *Group) Group(prefix string) *Group

Group creates a sub-group with the given prefix.

func (*Group) HEAD ΒΆ

func (g *Group) HEAD(pattern string, handlers ...Handler) *Group

HEAD registers a new route with the HEAD method.

func (*Group) Handle ΒΆ

func (g *Group) Handle(pattern, method string, handlers ...Handler) *Group

Handle registers a new route with the given pattern and method.

func (*Group) OPTIONS ΒΆ

func (g *Group) OPTIONS(pattern string, handlers ...Handler) *Group

OPTIONS registers a new route with the OPTIONS method.

func (*Group) PATCH ΒΆ

func (g *Group) PATCH(pattern string, handlers ...Handler) *Group

PATCH registers a new route with the PATCH method.

func (*Group) POST ΒΆ

func (g *Group) POST(pattern string, handlers ...Handler) *Group

POST registers a new route with the POST method.

func (*Group) PUT ΒΆ

func (g *Group) PUT(pattern string, handlers ...Handler) *Group

PUT registers a new route with the PUT method.

func (*Group) TRACE ΒΆ

func (g *Group) TRACE(pattern string, handlers ...Handler) *Group

TRACE registers a new route with the TRACE method.

func (*Group) Use ΒΆ

func (g *Group) Use(middleware ...interface{}) *Group

Use adds middleware to the group. It accepts middleware functions that take a context parameter.

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 map[string][]string

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 ΒΆ

func NewHeaderFromMap(m map[string][]string) *Header

NewHeaderFromMap creates a new Header from a map[string][]string. This optimized version avoids unnecessary copying of values when possible.

func UpdateHeaderFromMap ΒΆ

func UpdateHeaderFromMap(h *Header, m map[string][]string) *Header

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 ΒΆ

func (h Header) Add(key, value string)

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) Clone ΒΆ

func (h Header) Clone() Header

Clone returns a copy of h or nil if h is nil.

func (Header) Del ΒΆ

func (h Header) Del(key string)

Del deletes the values associated with key. The key is case insensitive; it is canonicalized by textproto.CanonicalMIMEHeaderKey.

func (Header) Get ΒΆ

func (h Header) Get(key string) string

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 ΒΆ

func (h Header) Set(key, value string)

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 ΒΆ

func (h Header) Values(key string) []string

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.

func (Header) Write ΒΆ

func (h Header) Write(w stringWriter) error

Write writes a header in wire format.

func (Header) WriteSubset ΒΆ

func (h Header) WriteSubset(w stringWriter, exclude map[string]bool) error

WriteSubset writes a header in wire format. If exclude is not nil, keys where exclude[key] == true are not written. This optimized version reduces allocations by avoiding unnecessary copying.

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 ΒΆ

func NewHttpError(code int, message string) *HttpError

NewHttpError creates a new HttpError with the given status code and message.

func NewHttpErrorWithError ΒΆ

func NewHttpErrorWithError(code int, message string, err error) *HttpError

NewHttpErrorWithError creates a new HttpError with the given status code, message, and error.

func (*HttpError) Error ΒΆ

func (e *HttpError) Error() string

Error implements the error interface.

func (*HttpError) Unwrap ΒΆ

func (e *HttpError) Unwrap() error

Unwrap returns the wrapped error, if any.

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

func (*Params) Get ΒΆ

func (p *Params) Get(key string) (string, bool)

Get retrieves a parameter value by key Returns the value and a boolean indicating if the key was found

func (*Params) Reset ΒΆ

func (p *Params) Reset()

Reset clears all parameters

func (*Params) Set ΒΆ

func (p *Params) Set(key, value string)

Set sets a parameter value by key If the key already exists, its value is updated If the key doesn't exist, a new entry is added

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 ΒΆ

func NewRequest(r *http.Request) *Request

NewRequest creates a new Request from an http.Request. It uses the requestPool to reuse Request objects when possible.

func (*Request) Context ΒΆ

func (r *Request) Context() context.Context

Context returns the request's context.

func (*Request) SetContext ΒΆ

func (r *Request) SetContext(ctx context.Context)

func (*Request) UserAgent ΒΆ

func (r *Request) UserAgent() string

UserAgent returns the client's User-Agent header.

func (*Request) WithContext ΒΆ

func (r *Request) WithContext(ctx context.Context) *Request

WithContext returns a shallow copy of r with its context changed to ctx.

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 NewRouter ΒΆ

func NewRouter() *Router

NewRouter creates a new Router.

func (*Router) CONNECT ΒΆ

func (r *Router) CONNECT(pattern string, handlers ...Handler) *Router

CONNECT registers a new route with the CONNECT method.

func (*Router) DELETE ΒΆ

func (r *Router) DELETE(pattern string, handlers ...Handler) *Router

DELETE registers a new route with the DELETE method.

func (*Router) GET ΒΆ

func (r *Router) GET(pattern string, handlers ...Handler) *Router

GET registers a new route with the GET method.

func (*Router) Group ΒΆ

func (r *Router) Group(prefix string) *Group

Group creates a new route group with the given prefix.

func (*Router) HEAD ΒΆ

func (r *Router) HEAD(pattern string, handlers ...Handler) *Router

HEAD registers a new route with the HEAD method.

func (*Router) Handle ΒΆ

func (r *Router) Handle(pattern, method string, handlers ...Handler) *Router

Handle registers a new route with the given pattern and method.

func (*Router) HandleStatic ΒΆ

func (r *Router) HandleStatic(prefix, root string, config ...Static) *Router

HandleStatic registers a new route for serving static files.

func (*Router) OPTIONS ΒΆ

func (r *Router) OPTIONS(pattern string, handlers ...Handler) *Router

OPTIONS registers a new route with the OPTIONS method.

func (*Router) PATCH ΒΆ

func (r *Router) PATCH(pattern string, handlers ...Handler) *Router

PATCH registers a new route with the PATCH method.

func (*Router) POST ΒΆ

func (r *Router) POST(pattern string, handlers ...Handler) *Router

POST registers a new route with the POST method.

func (*Router) PUT ΒΆ

func (r *Router) PUT(pattern string, handlers ...Handler) *Router

PUT registers a new route with the PUT method.

func (*Router) STATIC ΒΆ

func (r *Router) STATIC(prefix, root string, config ...Static) *Router

STATIC registers a new route with the GET method.

func (*Router) ServeHTTP ΒΆ

func (r *Router) ServeHTTP(ctx *Ctx, req *Request)

ServeHTTP implements a modified http.Handler interface that accepts a Ctx.

func (*Router) TRACE ΒΆ

func (r *Router) TRACE(pattern string, handlers ...Handler) *Router

TRACE registers a new route with the TRACE method.

func (*Router) Use ΒΆ

func (r *Router) Use(middleware ...interface{})

Use adds middleware to the router. It accepts middleware functions that take a context parameter.

type Server ΒΆ

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

Server represents an HTTP server.

func New ΒΆ

func New(config ...Config) *Server

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

func (*Server) CONNECT ΒΆ

func (s *Server) CONNECT(pattern string, handlers ...Handler) *Router

CONNECT registers a new route with the CONNECT method.

func (*Server) DELETE ΒΆ

func (s *Server) DELETE(pattern string, handlers ...Handler) *Router

DELETE registers a new route with the DELETE method.

func (*Server) GET ΒΆ

func (s *Server) GET(pattern string, handlers ...Handler) *Router

GET registers a new route with the GET method.

func (*Server) Group ΒΆ

func (s *Server) Group(prefix string) *Group

Group creates a new route group with the given prefix.

func (*Server) HEAD ΒΆ

func (s *Server) HEAD(pattern string, handlers ...Handler) *Router

HEAD registers a new route with the HEAD method.

func (*Server) Listen ΒΆ

func (s *Server) Listen(addr string) error

Listen starts the server and listens for incoming connections.

func (*Server) NotFound ΒΆ

func (s *Server) NotFound(handler Handler)

NotFound sets the handler for requests that don't match any route.

func (*Server) OPTIONS ΒΆ

func (s *Server) OPTIONS(pattern string, handlers ...Handler) *Router

OPTIONS registers a new route with the OPTIONS method.

func (*Server) PATCH ΒΆ

func (s *Server) PATCH(pattern string, handlers ...Handler) *Router

PATCH registers a new route with the PATCH method.

func (*Server) POST ΒΆ

func (s *Server) POST(pattern string, handlers ...Handler) *Router

POST registers a new route with the POST method.

func (*Server) PUT ΒΆ

func (s *Server) PUT(pattern string, handlers ...Handler) *Router

PUT registers a new route with the PUT method.

func (*Server) Router ΒΆ

func (s *Server) Router() *Router

func (*Server) STATIC ΒΆ

func (s *Server) STATIC(prefix, root string, config ...Static) *Router

STATIC registers a new route with the GET method.

func (*Server) Shutdown ΒΆ

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

Shutdown gracefully stops the server.

func (*Server) TRACE ΒΆ

func (s *Server) TRACE(pattern string, handlers ...Handler) *Router

TRACE registers a new route with the TRACE method.

func (*Server) Use ΒΆ

func (s *Server) Use(middleware ...interface{})

Use adds middleware to the router.

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.

func (*StorageError) Error ΒΆ

func (e *StorageError) Error() string

Error returns the error message.

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

Jump to

Keyboard shortcuts

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