core

package module
v1.17.3 Latest Latest
Warning

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

Go to latest
Published: Sep 2, 2025 License: MIT Imports: 19 Imported by: 22

README

gFly Core - Core Web written in Go

Copyright © 2023, gFly
https://www.gfly.dev
All rights reserved.
Setup gFly Core
mkdir myweb && cd myweb
go mod init myweb
go get -u github.com/gflydev/core@latest
Play with gFly
Create folder

Inside your application folder myweb

mkdir -p storage/tmp
mkdir -p storage/logs
mkdir -p storage/app
mkdir -p resources/views
mkdir -p resources/tls

Create static page

mkdir public
touch public/index.html

Content index.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
    <meta charset="UTF-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/>
    <title>gFly | Laravel inspired web framework written in Go</title>
</head>
<body>
    <h2>gFly | Laravel inspired web framework written in Go</h2>
</body>
</html>
Create app main.go
package main

import (
	"fmt"
	"github.com/gflydev/core"
	"github.com/gflydev/core/utils"
	_ "github.com/joho/godotenv/autoload"
)

// =========================================================================================
//                                     Default API
// =========================================================================================

// NewDefaultApi As a constructor to create new API.
func NewDefaultApi() *DefaultApi {
	return &DefaultApi{}
}

// DefaultApi API struct.
type DefaultApi struct {
	core.Api
}

func (h *DefaultApi) Handle(c *core.Ctx) error {
	return c.JSON(core.Data{
		"name":   core.AppName,
		"server": core.AppURL,
	})
}

// =========================================================================================
//                                     Home page
// =========================================================================================

// NewHomePage As a constructor to create a Home Page.
func NewHomePage() *HomePage {
	return &HomePage{}
}

type HomePage struct {
	core.Page
}

func (m *HomePage) Handle(c *core.Ctx) error {
	return c.HTML("<h2>Hello world</h2>")
}

// =========================================================================================
//                                     Routers
// =========================================================================================

func router(g core.IFly) {
	prefixAPI := fmt.Sprintf(
		"/%s/%s",
		utils.Getenv("API_PREFIX", "api"),
		utils.Getenv("API_VERSION", "v1"),
	)

	// API Routers
	g.Group(prefixAPI, func(apiRouter *core.Group) {
		apiRouter.GET("/info", NewDefaultApi())
	})

	// Web Routers
	g.GET("/home", NewHomePage())
}

// =========================================================================================
//                                     Application
// =========================================================================================

func main() {
	app := core.New()

	// Register middleware
	//app.RegisterMiddleware(hookMiddlewares)

	// Register router
	app.RegisterRouter(router)

	app.Run()
}
Run and Check

Run

go run main.go

Check API

curl -X 'GET' \
  'http://localhost:7789/api/v1/info' | jq

Note: Install jq tool to view JSON format

Check static page http://localhost:7789/index.html

Check dynamic page http://localhost:7789/home

Documentation

Index

Constants

View Source
const (
	// GlobalIpv4Addr represents the global IPv4 address used across the application
	GlobalIpv4Addr = "0.0.0.0"

	// SchemaHTTP specifies the HTTP schema
	SchemaHTTP = "http"

	// SchemaHTTPS specifies the HTTPS schema
	SchemaHTTPS = "https"

	// NetworkTCP represents the TCP network protocol
	NetworkTCP = "tcp"

	// NetworkTCP4 represents the IPv4-based TCP network protocol
	NetworkTCP4 = "tcp4"

	// NetworkTCP6 represents the IPv6-based TCP network protocol
	NetworkTCP6 = "tcp6"
)

Network

View Source
const (
	// StrGzip represents gzip compression type
	StrGzip = "gzip"

	// StrBr represents Brotli compression type
	StrBr = "br"

	// StrDeflate represents deflate compression type
	StrDeflate = "deflate"

	// StrBrotli represents Brotli compression type
	StrBrotli = "brotli"
)

Compression types

View Source
const (
	// CookieSameSiteDisabled indicates that the SameSite attribute is disabled in cookies
	CookieSameSiteDisabled = "disabled"

	// CookieSameSiteLaxMode indicates SameSite attribute set to Lax, which prevents cross-site usage
	// except for top-level navigations with safe HTTP methods
	CookieSameSiteLaxMode = "lax"

	// CookieSameSiteStrictMode indicates SameSite attribute set to Strict, restricting cross-site usage entirely
	CookieSameSiteStrictMode = "strict"

	// CookieSameSiteNoneMode indicates SameSite attribute set to None, allowing cross-site usage with Secure flag
	CookieSameSiteNoneMode = "none"
)

Cookie SameSite

View Source
const (
	// MIMETextXML represents the MIME type for XML text.
	MIMETextXML = "text/xml"
	// MIMETextHTML represents the MIME type for HTML text.
	MIMETextHTML = "text/html"
	// MIMETextPlain represents the MIME type for plain text.
	MIMETextPlain = "text/plain"
	// MIMETextJavaScript represents the MIME type for JavaScript text.
	MIMETextJavaScript = "text/javascript"
	// MIMEApplicationXML represents the MIME type for application XML.
	MIMEApplicationXML = "application/xml"
	// MIMEApplicationJSON represents the MIME type for application JSON.
	MIMEApplicationJSON = "application/json"
	// Deprecated: MIMEApplicationJavaScript use MIMETextJavaScript instead.
	MIMEApplicationJavaScript = "application/javascript"
	// MIMEApplicationForm represents the MIME type for form-urlencoded data.
	MIMEApplicationForm = "application/x-www-form-urlencoded"
	// MIMEOctetStream represents the MIME type for binary streams.
	MIMEOctetStream = "application/octet-stream"
	// MIMEMultipartForm represents the MIME type for multipart form data.
	MIMEMultipartForm = "multipart/form-data"

	// MIMETextXMLCharsetUTF8 represents the MIME type for XML text encoded in UTF-8.
	MIMETextXMLCharsetUTF8 = "text/xml; charset=utf-8"
	// MIMETextHTMLCharsetUTF8 represents the MIME type for HTML text encoded in UTF-8.
	MIMETextHTMLCharsetUTF8 = "text/html; charset=utf-8"
	// MIMETextPlainCharsetUTF8 represents the MIME type for plain text encoded in UTF-8.
	MIMETextPlainCharsetUTF8 = "text/plain; charset=utf-8"
	// MIMETextJavaScriptCharsetUTF8 represents the MIME type for JavaScript text encoded in UTF-8.
	MIMETextJavaScriptCharsetUTF8 = "text/javascript; charset=utf-8"
	// MIMEApplicationXMLCharsetUTF8 represents the MIME type for application XML encoded in UTF-8.
	MIMEApplicationXMLCharsetUTF8 = "application/xml; charset=utf-8"
	// MIMEApplicationJSONCharsetUTF8 represents the MIME type for application JSON encoded in UTF-8.
	MIMEApplicationJSONCharsetUTF8 = "application/json; charset=utf-8"
	// Deprecated: MIMEApplicationJavaScriptCharsetUTF8 use MIMETextJavaScriptCharsetUTF8 instead.
	MIMEApplicationJavaScriptCharsetUTF8 = "application/javascript; charset=utf-8"
)

MIME types that are commonly used

View Source
const (
	// MethodGet represents the GET HTTP method used to retrieve data from the server.
	// It is a safe, idempotent, and cacheable request method. (RFC 7231, 4.3.1)
	MethodGet = "GET"

	// MethodHead represents the HEAD HTTP method used to retrieve headers
	// without the response body. It is often used for metadata such as length. (RFC 7231, 4.3.2)
	MethodHead = "HEAD"

	// MethodPost represents the POST HTTP method used to send data to the server,
	// typically for creating or updating resources. (RFC 7231, 4.3.3)
	MethodPost = "POST"

	// MethodPut represents the PUT HTTP method used to update or create a resource
	// at the specified URI. It is idempotent. (RFC 7231, 4.3.4)
	MethodPut = "PUT"

	// MethodPatch represents the PATCH HTTP method used to apply partial modifications
	// to a resource. It is not necessarily idempotent. (RFC 5789)
	MethodPatch = "PATCH"

	// MethodDelete represents the DELETE HTTP method used to remove a resource
	// at the specified URI. It is idempotent. (RFC 7231, 4.3.5)
	MethodDelete = "DELETE"

	// MethodConnect represents the CONNECT HTTP method, typically used for
	// creating a network connection tunnel, often for HTTPS. (RFC 7231, 4.3.6)
	MethodConnect = "CONNECT"

	// MethodOptions represents the OPTIONS HTTP method, used to describe the
	// communication options for the target resource or server. (RFC 7231, 4.3.7)
	MethodOptions = "OPTIONS"

	// MethodTrace represents the TRACE HTTP method, used for diagnostic purposes.
	// It performs a message loop-back along the path to the target resource. (RFC 7231, 4.3.8)
	MethodTrace = "TRACE"

	// MethodUse represents a custom USE HTTP method.
	// Its purpose and implementation may vary based on application requirements.
	MethodUse = "USE"
)

HTTP methods were copied from net/http.

View Source
const (
	// StatusContinue indicates that the client should continue with its request. (RFC 9110, 15.2.1)
	StatusContinue = 100

	// StatusSwitchingProtocols indicates the server agrees to switch protocols. (RFC 9110, 15.2.2)
	StatusSwitchingProtocols = 101

	// StatusProcessing indicates that the request is being processed and no response is available yet. (RFC 2518, 10.1)
	StatusProcessing = 102

	// StatusEarlyHints provides hints to help the client start preloading resources while waiting for the final response. (RFC 8297)
	StatusEarlyHints = 103

	// StatusOK represents that the request has succeeded. (RFC 9110, 15.3.1)
	StatusOK = 200

	// StatusCreated indicates that the request has resulted in one or more new resources being created. (RFC 9110, 15.3.2)
	StatusCreated = 201

	// StatusAccepted indicates that the request has been received but not yet acted upon. (RFC 9110, 15.3.3)
	StatusAccepted = 202

	// StatusNonAuthoritativeInformation indicates that the returned metadata is not from the origin server. (RFC 9110, 15.3.4)
	StatusNonAuthoritativeInformation = 203

	// StatusNoContent indicates that the server successfully fulfilled the request, but there is no content to send in response. (RFC 9110, 15.3.5)
	StatusNoContent = 204

	// StatusResetContent indicates that the server successfully fulfilled the request and expects the user agent to reset the document view. (RFC 9110, 15.3.6)
	StatusResetContent = 205

	// StatusPartialContent indicates that the server successfully fulfilled a range request for the target resource. (RFC 9110, 15.3.7)
	StatusPartialContent = 206

	// StatusMultiStatus indicates multiple status codes for a single request involving multiple operations. (RFC 4918, 11.1)
	StatusMultiStatus = 207

	// StatusAlreadyReported indicates that the members of a DAV binding have already been reported in a previous reply. (RFC 5842, 7.1)
	StatusAlreadyReported = 208

	// StatusIMUsed indicates that the server fulfilled a GET request including instance-manipulations. (RFC 3229, 10.4.1)
	StatusIMUsed = 226

	// StatusMultipleChoices indicates multiple options for the requested resource. (RFC 9110, 15.4.1)
	StatusMultipleChoices = 300

	// StatusMovedPermanently indicates that the target resource has been assigned a new permanent URI. (RFC 9110, 15.4.2)
	StatusMovedPermanently = 301

	// StatusFound indicates the target resource resides temporarily under a different URI and may change in the future. (RFC 9110, 15.4.3)
	StatusFound = 302

	// StatusSeeOther indicates that the server redirects the client to a different URI for the requested resource. (RFC 9110, 15.4.4)
	StatusSeeOther = 303

	// StatusNotModified indicates that the cached version of the requested resource is still valid. (RFC 9110, 15.4.5)
	StatusNotModified = 304

	// StatusUseProxy is deprecated and was reserved for proxy usage. (RFC 9110, 15.4.6)
	StatusUseProxy = 305

	// StatusSwitchProxy was used to indicate a new proxy, but it is unused. (RFC 9110, 15.4.7)
	StatusSwitchProxy = 306

	// StatusTemporaryRedirect indicates that the target resource resides temporarily under a different URI. (RFC 9110, 15.4.8)
	StatusTemporaryRedirect = 307

	// StatusPermanentRedirect indicates that the target resource has been assigned a permanent URI. (RFC 9110, 15.4.9)
	StatusPermanentRedirect = 308

	// StatusBadRequest indicates that the server could not understand the request due to invalid syntax. (RFC 9110, 15.5.1)
	StatusBadRequest = 400

	// StatusUnauthorized indicates that the request requires user authentication. (RFC 9110, 15.5.2)
	StatusUnauthorized = 401

	// StatusPaymentRequired is reserved for future use. (RFC 9110, 15.5.3)
	StatusPaymentRequired = 402

	// StatusForbidden indicates that the server understands the request but refuses to authorize it. (RFC 9110, 15.5.4)
	StatusForbidden = 403

	// StatusNotFound indicates that the server cannot find the requested resource. (RFC 9110, 15.5.5)
	StatusNotFound = 404

	// StatusMethodNotAllowed indicates that the request method is not supported for the target resource. (RFC 9110, 15.5.6)
	StatusMethodNotAllowed = 405

	// StatusNotAcceptable indicates that no resource is available matching the criteria specified by the request headers. (RFC 9110, 15.5.7)
	StatusNotAcceptable = 406

	// StatusProxyAuthRequired indicates that the request must be authenticated with a proxy. (RFC 9110, 15.5.8)
	StatusProxyAuthRequired = 407

	// StatusRequestTimeout indicates that the server timed out waiting for the request. (RFC 9110, 15.5.9)
	StatusRequestTimeout = 408

	// StatusConflict indicates that the request conflicts with the current state of the resource. (RFC 9110, 15.5.10)
	StatusConflict = 409

	// StatusGone indicates that the target resource is no longer available at the server. (RFC 9110, 15.5.11)
	StatusGone = 410

	// StatusLengthRequired indicates that the server requires a Content-Length header field in the request. (RFC 9110, 15.5.12)
	StatusLengthRequired = 411

	// StatusPreconditionFailed indicates that a precondition in the request header fields evaluated to false. (RFC 9110, 15.5.13)
	StatusPreconditionFailed = 412

	// StatusRequestEntityTooLarge indicates that the request entity is larger than the server is willing or able to process. (RFC 9110, 15.5.14)
	StatusRequestEntityTooLarge = 413

	// StatusRequestURITooLong indicates that the request URI is longer than the server is willing to interpret. (RFC 9110, 15.5.15)
	StatusRequestURITooLong = 414

	// StatusUnsupportedMediaType indicates that the request entity's media type is unsupported by the server. (RFC 9110, 15.5.16)
	StatusUnsupportedMediaType = 415

	// StatusRequestedRangeNotSatisfiable indicates that the requested range cannot be fulfilled. (RFC 9110, 15.5.17)
	StatusRequestedRangeNotSatisfiable = 416

	// StatusExpectationFailed indicates that the server cannot meet the requirements of the Expect request-header field. (RFC 9110, 15.5.18)
	StatusExpectationFailed = 417

	// StatusTeapot is a humorous response code. (RFC 9110, 15.5.19)
	StatusTeapot = 418

	// StatusMisdirectedRequest indicates that the server is not able to produce a response due to inappropriate routing. (RFC 9110, 15.5.20)
	StatusMisdirectedRequest = 421

	// StatusUnprocessableEntity indicates that the server understands the content type but cannot process the request. (RFC 9110, 15.5.21)
	StatusUnprocessableEntity = 422

	// StatusLocked indicates that the resource is currently locked. (RFC 4918, 11.3)
	StatusLocked = 423

	// StatusFailedDependency indicates that the request failed due to a dependency on another request. (RFC 4918, 11.4)
	StatusFailedDependency = 424

	// StatusTooEarly indicates that the server is unwilling to risk processing a replayed request. (RFC 8470, 5.2.)
	StatusTooEarly = 425

	// StatusUpgradeRequired indicates that the client should switch to a different protocol. (RFC 9110, 15.5.22)
	StatusUpgradeRequired = 426

	// StatusPreconditionRequired indicates that the server requires the request to be conditional. (RFC 6585, 3)
	StatusPreconditionRequired = 428

	// StatusTooManyRequests indicates that the user has sent too many requests in a given amount of time. (RFC 6585, 4)
	StatusTooManyRequests = 429

	// StatusRequestHeaderFieldsTooLarge indicates that the server refuses to process the request because the header fields are too large. (RFC 6585, 5)
	StatusRequestHeaderFieldsTooLarge = 431

	// StatusUnavailableForLegalReasons indicates access to the resource is denied for legal reasons. (RFC 7725, 3)
	StatusUnavailableForLegalReasons = 451

	// StatusInternalServerError indicates that the server encountered an unexpected condition that prevented it from fulfilling the request. (RFC 9110, 15.6.1)
	StatusInternalServerError = 500

	// StatusNotImplemented indicates that the server does not support the functionality required to fulfill the request. (RFC 9110, 15.6.2)
	StatusNotImplemented = 501

	// StatusBadGateway indicates that the server, acting as a gateway or proxy, received an invalid response from an upstream server. (RFC 9110, 15.6.3)
	StatusBadGateway = 502

	// StatusServiceUnavailable indicates that the server is temporarily unable to handle the request due to maintenance or overload. (RFC 9110, 15.6.4)
	StatusServiceUnavailable = 503

	// StatusGatewayTimeout indicates that the server, acting as a gateway or proxy, did not receive a timely response from an upstream server. (RFC 9110, 15.6.5)
	StatusGatewayTimeout = 504

	// StatusHTTPVersionNotSupported indicates that the server does not support the HTTP protocol version used in the request. (RFC 9110, 15.6.6)
	StatusHTTPVersionNotSupported = 505

	// StatusVariantAlsoNegotiates indicates that the server detects loop negotiation. (RFC 2295, 8.1)
	StatusVariantAlsoNegotiates = 506

	// StatusInsufficientStorage indicates that the server is unable to store the representation needed to complete the request. (RFC 4918, 11.5)
	StatusInsufficientStorage = 507

	// StatusLoopDetected indicates that the server detected an infinite loop while processing the request. (RFC 5842, 7.2)
	StatusLoopDetected = 508

	// StatusNotExtended indicates that further extensions to the request are required for the server to fulfill it. (RFC 2774, 7)
	StatusNotExtended = 510

	// StatusNetworkAuthenticationRequired indicates that the client needs to authenticate to gain network access. (RFC 6585, 6)
	StatusNetworkAuthenticationRequired = 511
)

HTTP status codes were copied from net/http with the following updates: - Rename StatusNonAuthoritativeInfo to StatusNonAuthoritativeInformation - Add StatusSwitchProxy (306) NOTE: Keep this list in sync with statusMessage

View Source
const (
	// HeaderAuthorization represents the HTTP Authorization header.
	HeaderAuthorization = "Authorization"
	// HeaderProxyAuthenticate represents the HTTP Proxy-Authenticate header.
	HeaderProxyAuthenticate = "Proxy-Authenticate"
	// HeaderProxyAuthorization represents the HTTP Proxy-Authorization header.
	HeaderProxyAuthorization = "Proxy-Authorization"
	// HeaderWWWAuthenticate represents the HTTP WWW-Authenticate header.
	HeaderWWWAuthenticate = "WWW-Authenticate"
	// HeaderAge represents the HTTP Age header.
	HeaderAge = "Age"
	// HeaderCacheControl represents the HTTP Cache-Control header.
	HeaderCacheControl = "Cache-Control"
	// HeaderClearSiteData represents the HTTP Clear-Site-Data header.
	HeaderClearSiteData = "Clear-Site-Data"
	// HeaderExpires represents the HTTP Expires header.
	HeaderExpires = "Expires"
	// HeaderPragma represents the HTTP Pragma header.
	HeaderPragma = "Pragma"
	// HeaderWarning represents the HTTP Warning header.
	HeaderWarning = "Warning"
	// HeaderAcceptCH represents the HTTP Accept-CH header.
	HeaderAcceptCH = "Accept-CH"
	// HeaderAcceptCHLifetime represents the HTTP Accept-CH-Lifetime header.
	HeaderAcceptCHLifetime = "Accept-CH-Lifetime"
	// HeaderContentDPR represents the HTTP Content-DPR header.
	HeaderContentDPR = "Content-DPR"
	// HeaderDPR represents the HTTP DPR header.
	HeaderDPR = "DPR"
	// HeaderEarlyData represents the HTTP Early-Data header.
	HeaderEarlyData = "Early-Data"
	// HeaderSaveData represents the HTTP Save-Data header.
	HeaderSaveData = "Save-Data"
	// HeaderViewportWidth represents the HTTP Viewport-Width header.
	HeaderViewportWidth = "Viewport-Width"
	// HeaderWidth represents the HTTP Width header.
	HeaderWidth = "Width"
	// HeaderETag represents the HTTP ETag header.
	HeaderETag = "ETag"
	// HeaderIfMatch represents the HTTP If-Match header.
	HeaderIfMatch = "If-Match"
	// HeaderIfModifiedSince represents the HTTP If-Modified-Since header.
	HeaderIfModifiedSince = "If-Modified-Since"
	// HeaderIfNoneMatch represents the HTTP If-None-Match header.
	HeaderIfNoneMatch = "If-None-Match"
	// HeaderIfUnmodifiedSince represents the HTTP If-Unmodified-Since header.
	HeaderIfUnmodifiedSince = "If-Unmodified-Since"
	// HeaderLastModified represents the HTTP Last-Modified header.
	HeaderLastModified = "Last-Modified"
	// HeaderVary represents the HTTP Vary header.
	HeaderVary = "Vary"
	// HeaderConnection represents the HTTP Connection header.
	HeaderConnection = "Connection"
	// HeaderKeepAlive represents the HTTP Keep-Alive header.
	HeaderKeepAlive = "Keep-Alive"
	// HeaderAccept represents the HTTP Accept header.
	HeaderAccept = "Accept"
	// HeaderAcceptCharset represents the HTTP Accept-Charset header.
	HeaderAcceptCharset = "Accept-Charset"
	// HeaderAcceptEncoding represents the HTTP Accept-Encoding header.
	HeaderAcceptEncoding = "Accept-Encoding"
	// HeaderAcceptLanguage represents the HTTP Accept-Language header.
	HeaderAcceptLanguage = "Accept-Language"
	// HeaderCookie represents the HTTP Cookie header.
	HeaderCookie = "Cookie"
	// HeaderExpect represents the HTTP Expect header.
	HeaderExpect = "Expect"
	// HeaderMaxForwards represents the HTTP Max-Forwards header.
	HeaderMaxForwards = "Max-Forwards"
	// HeaderSetCookie represents the HTTP Set-Cookie header.
	HeaderSetCookie = "Set-Cookie"
	// HeaderAccessControlAllowCredentials represents the HTTP Access-Control-Allow-Credentials header.
	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	// HeaderAccessControlAllowHeaders represents the HTTP Access-Control-Allow-Headers header.
	HeaderAccessControlAllowHeaders = "Access-Control-Allow-Headers"
	// HeaderAccessControlAllowMethods represents the HTTP Access-Control-Allow-Methods header.
	HeaderAccessControlAllowMethods = "Access-Control-Allow-Methods"
	// HeaderAccessControlAllowOrigin represents the HTTP Access-Control-Allow-Origin header.
	HeaderAccessControlAllowOrigin = "Access-Control-Allow-Origin"
	// HeaderAccessControlExposeHeaders represents the HTTP Access-Control-Expose-Headers header.
	HeaderAccessControlExposeHeaders = "Access-Control-Expose-Headers"
	// HeaderAccessControlMaxAge represents the HTTP Access-Control-Max-Age header.
	HeaderAccessControlMaxAge = "Access-Control-Max-Age"
	// HeaderAccessControlRequestHeaders represents the HTTP Access-Control-Request-Headers header.
	HeaderAccessControlRequestHeaders = "Access-Control-Request-Headers"
	// HeaderAccessControlRequestMethod represents the HTTP Access-Control-Request-Method header.
	HeaderAccessControlRequestMethod = "Access-Control-Request-Method"
	// HeaderOrigin represents the HTTP Origin header.
	HeaderOrigin = "Origin"
	// HeaderTimingAllowOrigin represents the HTTP Timing-Allow-Origin header.
	HeaderTimingAllowOrigin = "Timing-Allow-Origin"
	// HeaderXPermittedCrossDomainPolicies represents the HTTP X-Permitted-Cross-Domain-Policies header.
	HeaderXPermittedCrossDomainPolicies = "X-Permitted-Cross-Domain-Policies"
	// HeaderDNT represents the HTTP DNT (Do Not Track) header.
	HeaderDNT = "DNT"
	// HeaderTk represents the HTTP Tk (Tracking Status Value) header.
	HeaderTk = "Tk"
	// HeaderContentDisposition represents the HTTP Content-Disposition header.
	HeaderContentDisposition = "Content-Disposition"
	// HeaderContentEncoding represents the HTTP Content-Encoding header.
	HeaderContentEncoding = "Content-Encoding"
	// HeaderContentLanguage represents the HTTP Content-Language header.
	HeaderContentLanguage = "Content-Language"
	// HeaderContentLength represents the HTTP Content-Length header.
	HeaderContentLength = "Content-Length"
	// HeaderContentLocation represents the HTTP Content-Location header.
	HeaderContentLocation = "Content-Location"
	// HeaderContentType represents the HTTP Content-Type header.
	HeaderContentType = "Content-Type"
	// HeaderForwarded represents the HTTP Forwarded header.
	HeaderForwarded = "Forwarded"
	// HeaderVia represents the HTTP Via header.
	HeaderVia = "Via"
	// HeaderXForwardedFor represents the HTTP X-Forwarded-For header.
	HeaderXForwardedFor = "X-Forwarded-For"
	// HeaderXForwardedHost represents the HTTP X-Forwarded-Host header.
	HeaderXForwardedHost = "X-Forwarded-Host"
	// HeaderXForwardedProto represents the HTTP X-Forwarded-Proto header.
	HeaderXForwardedProto = "X-Forwarded-Proto"
	// HeaderXForwardedProtocol represents the HTTP X-Forwarded-Protocol header.
	HeaderXForwardedProtocol = "X-Forwarded-Protocol"
	// HeaderXForwardedSsl represents the HTTP X-Forwarded-Ssl header.
	HeaderXForwardedSsl = "X-Forwarded-Ssl"
	// HeaderXUrlScheme represents the HTTP X-Url-Scheme header.
	HeaderXUrlScheme = "X-Url-Scheme"
	// HeaderLocation represents the HTTP Location header.
	HeaderLocation = "Location"
	// HeaderFrom represents the HTTP From header.
	HeaderFrom = "From"
	// HeaderHost represents the HTTP Host header.
	HeaderHost = "Host"
	// HeaderReferer represents the HTTP Referer header.
	HeaderReferer = "Referer"
	// HeaderReferrerPolicy represents the HTTP Referrer-Policy header.
	HeaderReferrerPolicy = "Referrer-Policy"
	// HeaderUserAgent represents the HTTP User-Agent header.
	HeaderUserAgent = "User-Agent"
	// HeaderAllow represents the HTTP Allow header.
	HeaderAllow = "Allow"
	// HeaderServer represents the HTTP Server header.
	HeaderServer = "Server"
	// HeaderAcceptRanges represents the HTTP Accept-Ranges header.
	HeaderAcceptRanges = "Accept-Ranges"
	// HeaderContentRange represents the HTTP Content-Range header.
	HeaderContentRange = "Content-Range"
	// HeaderIfRange represents the HTTP If-Range header.
	HeaderIfRange = "If-Range"
	// HeaderRange represents the HTTP Range header.
	HeaderRange = "Range"
	// HeaderContentSecurityPolicy represents the HTTP Content-Security-Policy header.
	HeaderContentSecurityPolicy = "Content-Security-Policy"
	// HeaderContentSecurityPolicyReportOnly represents the HTTP Content-Security-Policy-Report-Only header.
	HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
	// HeaderCrossOriginResourcePolicy represents the HTTP Cross-Origin-Resource-Policy header.
	HeaderCrossOriginResourcePolicy = "Cross-Origin-Resource-Policy"
	// HeaderExpectCT represents the HTTP Expect-CT header.
	HeaderExpectCT = "Expect-CT"
	// HeaderFeaturePolicy represents the deprecated HTTP Feature-Policy header.
	// Deprecated: use HeaderPermissionsPolicy instead.
	HeaderFeaturePolicy = "Feature-Policy"

	// HeaderPermissionsPolicy represents the HTTP Permissions-Policy header.
	HeaderPermissionsPolicy = "Permissions-Policy"

	// HeaderPublicKeyPins represents the HTTP Public-Key-Pins header.
	HeaderPublicKeyPins = "Public-Key-Pins"

	// HeaderPublicKeyPinsReportOnly represents the HTTP Public-Key-Pins-Report-Only header.
	HeaderPublicKeyPinsReportOnly = "Public-Key-Pins-Report-Only"

	// HeaderStrictTransportSecurity represents the HTTP Strict-Transport-Security header.
	HeaderStrictTransportSecurity = "Strict-Transport-Security"

	// HeaderUpgradeInsecureRequests represents the HTTP Upgrade-Insecure-Requests header.
	HeaderUpgradeInsecureRequests = "Upgrade-Insecure-Requests"

	// HeaderXContentTypeOptions represents the HTTP X-Content-Type-Options header.
	HeaderXContentTypeOptions = "X-Content-Type-Options"

	// HeaderXDownloadOptions represents the HTTP X-Download-Options header.
	HeaderXDownloadOptions = "X-Download-Options"

	// HeaderXFrameOptions represents the HTTP X-Frame-Options header.
	HeaderXFrameOptions = "X-Frame-Options"

	// HeaderXPoweredBy represents the HTTP X-Powered-By header.
	HeaderXPoweredBy = "X-Powered-By"

	// HeaderXXSSProtection represents the HTTP X-XSS-Protection header.
	HeaderXXSSProtection = "X-XSS-Protection"

	// HeaderLastEventID represents the HTTP Last-Event-ID header.
	HeaderLastEventID = "Last-Event-ID"

	// HeaderNEL represents the HTTP NEL (Network Error Logging) header.
	HeaderNEL = "NEL"

	// HeaderPingFrom represents the HTTP Ping-From header.
	HeaderPingFrom = "Ping-From"

	// HeaderPingTo represents the HTTP Ping-To header.
	HeaderPingTo = "Ping-To"

	// HeaderReportTo represents the HTTP Report-To header.
	HeaderReportTo = "Report-To"

	// HeaderTE represents the HTTP TE (Transfer Encoding) header.
	HeaderTE = "TE"

	// HeaderTrailer represents the HTTP Trailer header.
	HeaderTrailer = "Trailer"

	// HeaderTransferEncoding represents the HTTP Transfer-Encoding header.
	HeaderTransferEncoding = "Transfer-Encoding"

	// HeaderSecWebSocketAccept represents the HTTP Sec-WebSocket-Accept header.
	HeaderSecWebSocketAccept = "Sec-WebSocket-Accept"

	// HeaderSecWebSocketExtensions represents the HTTP Sec-WebSocket-Extensions header.
	HeaderSecWebSocketExtensions = "Sec-WebSocket-Extensions"

	// HeaderSecWebSocketKey represents the HTTP Sec-WebSocket-Key header.
	HeaderSecWebSocketKey = "Sec-WebSocket-Key"

	// HeaderSecWebSocketProtocol represents the HTTP Sec-WebSocket-Protocol header.
	HeaderSecWebSocketProtocol = "Sec-WebSocket-Protocol"

	// HeaderSecWebSocketVersion represents the HTTP Sec-WebSocket-Version header.
	HeaderSecWebSocketVersion = "Sec-WebSocket-Version"

	// HeaderAcceptPatch represents the HTTP Accept-Patch header.
	HeaderAcceptPatch = "Accept-Patch"

	// HeaderAcceptPushPolicy represents the HTTP Accept-Push-Policy header.
	HeaderAcceptPushPolicy = "Accept-Push-Policy"

	// HeaderAcceptSignature represents the HTTP Accept-Signature header.
	HeaderAcceptSignature = "Accept-Signature"

	// HeaderAltSvc represents the HTTP Alt-Svc header.
	HeaderAltSvc = "Alt-Svc"

	// HeaderDate represents the HTTP Date header.
	HeaderDate = "Date"

	// HeaderIndex represents the HTTP Index header.
	HeaderIndex = "Index"

	// HeaderLargeAllocation represents the HTTP Large-Allocation header.
	HeaderLargeAllocation = "Large-Allocation"

	// HeaderLink represents the HTTP Link header.
	HeaderLink = "Link"

	// HeaderPushPolicy represents the HTTP Push-Policy header.
	HeaderPushPolicy = "Push-Policy"

	// HeaderRetryAfter represents the HTTP Retry-After header.
	HeaderRetryAfter = "Retry-After"

	// HeaderServerTiming represents the HTTP Server-Timing header.
	HeaderServerTiming = "Server-Timing"

	// HeaderSignature represents the HTTP Signature header.
	HeaderSignature = "Signature"

	// HeaderSignedHeaders represents the HTTP Signed-Headers header.
	HeaderSignedHeaders = "Signed-Headers"

	// HeaderSourceMap represents the HTTP SourceMap header.
	HeaderSourceMap = "SourceMap"

	// HeaderUpgrade represents the HTTP Upgrade header.
	HeaderUpgrade = "Upgrade"

	// HeaderXDNSPrefetchControl represents the HTTP X-DNS-Prefetch-Control header.
	HeaderXDNSPrefetchControl = "X-DNS-Prefetch-Control"

	// HeaderXPingBack represents the HTTP X-Pingback header.
	HeaderXPingBack = "X-Pingback"

	// HeaderXRequestID represents the HTTP X-Request-ID header.
	HeaderXRequestID = "X-Request-ID"

	// HeaderXRequestedWith represents the HTTP X-Requested-With header.
	HeaderXRequestedWith = "X-Requested-With"

	// HeaderXRobotsTag represents the HTTP X-Robots-Tag header.
	HeaderXRobotsTag = "X-Robots-Tag"

	// HeaderXUACompatible represents the HTTP X-UA-Compatible header.
	HeaderXUACompatible = "X-UA-Compatible"
)

HTTP Headers were copied from net/http.

View Source
const (
	// ParamTypePost represents the form parameter type
	ParamTypePost = "post"

	// ParamTypeQuery represents the query parameter type
	ParamTypeQuery = "query"

	// ParamTypeBody represents the JSON body parameter type
	ParamTypeBody = "body"
)

Parameter types used in request parameter operations

View Source
const MethodWild = "*"

MethodWild wild HTTP method

View Source
const (
	// Version indicates the version of the framework
	Version = "v1.17.1"
)

Version of the current gFly application

Variables

View Source
var (

	// AppName holds the application name fetched from `APP_NAME` environment variable or defaults to "gFly".
	AppName = utils.Getenv("APP_NAME", "gFly")
	// AppCode holds the application code fetched from `APP_CODE` environment variable or defaults to "gfly".
	AppCode = utils.Getenv("APP_CODE", "gfly")
	// AppURL holds the application URL fetched from `APP_URL` environment variable or defaults to "http://localhost:7789".
	AppURL = utils.Getenv("APP_URL", "http://localhost:7789")
	// AppEnv holds the application environment fetched from `APP_ENV` environment variable or defaults to "local".
	AppEnv = utils.Getenv("APP_ENV", "local")
	// AppDebug indicates if the application is in debug mode, fetched from `APP_DEBUG` environment variable or defaults to true.
	AppDebug = utils.Getenv("APP_DEBUG", true)

	// StorageDir specifies the directory for application storage, fetched from `STORAGE_DIR` environment variable or defaults to "storage".
	StorageDir = utils.Getenv("STORAGE_DIR", "storage") // Directory `{APP}/storage`
	// TempDir specifies the temporary directory within the storage, fetched from `TEMP_DIR` environment variable or defaults to "storage/tmp".
	TempDir = utils.Getenv("TEMP_DIR", "storage/tmp") // Directory `{APP}/storage/temp`
	// LogDir specifies the directory for logs within the storage, fetched from `LOG_DIR` environment variable or defaults to "storage/logs".
	LogDir = utils.Getenv("LOG_DIR", "storage/logs") // Directory `{APP}/storage/log`
	// AppDir specifies the application-specific directory within the storage, fetched from `APP_DIR` environment variable or defaults to "storage/app".
	AppDir = utils.Getenv("APP_DIR", "storage/app") // Directory `{APP}/storage/app`

)
View Source
var DefaultConfig = Config{
	AppName:                       "Laravel inspired web framework written in Go",
	Name:                          "gFly",
	Concurrency:                   256 * 1024,
	ReadTimeout:                   60 * 60 * time.Second,
	WriteTimeout:                  60 * 60 * time.Second,
	IdleTimeout:                   60 * 60 * time.Second,
	ReadBufferSize:                4096 * 10,
	WriteBufferSize:               4096 * 10,
	NoDefaultDate:                 false,
	NoDefaultContentType:          false,
	DisableHeaderNamesNormalizing: false,
	DisableKeepalive:              false,
	MaxRequestBodySize:            4 * 1024 * 1024,
	NoDefaultServerHeader:         false,
	GetOnly:                       false,
	ReduceMemoryUsage:             false,
	StreamRequestBody:             true,
	DisablePreParseMultipartForm:  true,
	DisableStartupMessage:         false,
	Network:                       NetworkTCP4,
	Prefork:                       false,
	CompressedFileSuffix:          ".gz",
}

DefaultConfig holds the default configuration settings for the gFly framework.

Fields:

  • AppName (string): Application name. Default: "Laravel inspired web framework written in Go".
  • Name (string): Server name for sending in response headers. Default: "gFly".
  • Concurrency (int): Maximum number of concurrent connections. Default: 256 * 1024.
  • ReadTimeout (time.Duration): Request read timeout. Default: 60 minutes.
  • WriteTimeout (time.Duration): Response write timeout. Default: 60 minutes.
  • IdleTimeout (time.Duration): Maximum time to wait for the next request when keep-alive is enabled. Default: 60 minutes.
  • ReadBufferSize (int): Buffer size for request reading. Default: 40,960 bytes.
  • WriteBufferSize (int): Buffer size for response writing. Default: 40,960 bytes.
  • NoDefaultDate (bool): Exclude default "Date" header from the response. Default: false.
  • NoDefaultContentType (bool): Exclude default "Content-Type" header from the response. Default: false.
  • DisableHeaderNamesNormalizing (bool): Disable normalization of header names. Default: false.
  • DisableKeepalive (bool): Disable keep-alive connections. Default: false.
  • MaxRequestBodySize (int): Maximum request body size. Default: 4 MB.
  • NoDefaultServerHeader (bool): Exclude default "Server" header from the response. Default: false.
  • GetOnly (bool): Reject all non-GET requests. Default: false.
  • ReduceMemoryUsage (bool): Reduce memory usage aggressively. Default: false.
  • StreamRequestBody (bool): Enable request body streaming for large requests. Default: true.
  • DisablePreParseMultipartForm (bool): Do not pre-parse multipart form data. Default: true.
  • DisableStartupMessage (bool): Do not print startup messages. Default: false.
  • Network (string): Network type ("tcp", "tcp4", "tcp6"). Default: "tcp4".
  • Prefork (bool): Enable prefork with multiple Go processes. Default: false.
  • CompressedFileSuffix (string): Suffix for compressed file names. Default: ".gz".

Functions

func RegisterSession added in v1.9.0

func RegisterSession(s ISession)

RegisterSession registers a custom implementation of the ISession interface. Parameters:

  • s: The custom implementation of the ISession interface.

func RegisterView added in v1.8.0

func RegisterView(v IView)

RegisterView registers a custom view engine by setting the global `view` instance to `v`. This should be called during application initialization to use a specific view engine.

Parameters:

  • v: An implementation of the IView interface representing the custom view engine.

Types

type Api

type Api struct {
	Endpoint
}

Api Abstract API.

Inherits:

  • Endpoint: Base endpoint for API handling logic.

type Config

type Config struct {
	// AppName specifies the application name.
	//
	// Default: "Laravel inspired web framework written in Go".
	AppName string

	// Name specifies the server name for sending in response headers.
	//
	// Default: "gFly".
	Name string

	// Concurrency defines the maximum number of concurrent connections the server may serve.
	// The maximum number of concurrent connections the server may serve.
	//
	// DefaultConcurrency is used if not set.
	//
	// Concurrency only works if you either call Serve once, or only ServeConn multiple times.
	// It works with ListenAndServe as well.
	// Default: 256 * 1024.
	Concurrency int

	// ReadTimeout specifies the maximum duration allowed to read the full request, including the body.
	// The connection's read deadline is reset when a connection opens or for keep-alive connections,
	// after the first byte has been read.
	//
	// Default: 60 minutes.
	ReadTimeout time.Duration

	// WriteTimeout specifies the maximum duration before timing out writes of the response.
	// It is reset after the request handler has returned.
	//
	// Default: 60 minutes.
	WriteTimeout time.Duration

	// IdleTimeout defines the maximum duration to wait for the next request when keep-alive is enabled.
	// If IdleTimeout is zero, the value of ReadTimeout is used.
	//
	// Default: 60 minutes.
	IdleTimeout time.Duration

	// ReadBufferSize specifies the buffer size for request reading, which also limits the maximum header size.
	// Increase this buffer if clients send large RequestURIs or headers.
	//
	// Default: 40,960 bytes.
	ReadBufferSize int

	// WriteBufferSize specifies the buffer size for response writing.
	//
	// Default: 40,960 bytes.
	WriteBufferSize int

	// NoDefaultDate determines whether the default "Date" header should be excluded from the response.
	//
	// Default: false.
	NoDefaultDate bool

	// NoDefaultContentType determines whether the default "Content-Type" header should be excluded from the response.
	//
	// Default: false.
	NoDefaultContentType bool

	// DisableHeaderNamesNormalizing determines whether header names should be passed as-is without normalization.
	// By default, header names are normalized.
	//
	// Default: false.
	DisableHeaderNamesNormalizing bool

	// DisableKeepalive indicates whether to disable keep-alive connections.
	//
	// Default: false.
	DisableKeepalive bool

	// MaxRequestBodySize specifies the maximum size of the request body.
	// A zero value means the default value will be honored.
	//
	// Default: 4 MB.
	MaxRequestBodySize int

	// NoDefaultServerHeader determines whether the default "Server" header should be excluded from the response.
	//
	// Default: false.
	NoDefaultServerHeader bool

	// GetOnly rejects all non-GET requests if set to true. Useful as anti-DoS protection for servers
	// that only accept GET and HEAD requests. Request size is limited by ReadBufferSize when enabled.
	//
	// Default: false.
	GetOnly bool

	// ReduceMemoryUsage aggressively reduces memory usage at the cost of higher CPU usage.
	// Only enable if serving mostly idle keep-alive connections.
	//
	// Default: false.
	ReduceMemoryUsage bool

	// StreamRequestBody enables request body streaming and calls the handler sooner
	// when the body exceeds the current limit.
	//
	// Default: true.
	StreamRequestBody bool

	// DisablePreParseMultipartForm determines whether to avoid pre-parsing multipart form data.
	// Useful for treating multipart form data as binary or controlling when data is parsed.
	//
	// Default: true.
	DisablePreParseMultipartForm bool

	// DisableStartupMessage determines whether to suppress the printing of "gFly" ASCII art and listening address
	// during startup.
	//
	// Default: false.
	DisableStartupMessage bool

	// Network specifies the network type ("tcp", "tcp4", "tcp6").
	// When prefork is true, only "tcp4" and "tcp6" are allowed.
	//
	// Default: "tcp4".
	Network string

	// Prefork enables preforking with multiple Go processes listening on the same port.
	//
	// Default: false.
	Prefork bool

	// CompressedFileSuffix specifies a suffix to the file name when saving the resulting compressed file.
	//
	// Default: ".gz".
	CompressedFileSuffix string
}

type Ctx

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

Ctx HTTP request context

func (*Ctx) AddParam added in v1.17.0

func (c *Ctx) AddParam(key, value string, paramType ...string) IRequestData

AddParam adds a parameter to the request.

Parameters:

  • key (string): The key of the parameter to add.
  • value (string): The value to associate with the key.
  • paramType (...string): Optional parameter type. Can be ParamTypePost or ParamTypeQuery or ParamTypeBody. Default is both.

Returns:

  • IRequestData: The current request data interface for chaining.

func (*Ctx) Compress

func (c *Ctx) Compress(body []byte) error

Compress compresses the HTTP response body using the best available compression method based on the "Accept-Encoding" request header.

TODO Need more checking

Parameters:

  • body ([]byte): The raw response body to be compressed.

Returns:

  • error: An error if the compression process fails or encounters issues.

func (*Ctx) ContentType

func (c *Ctx) ContentType(mime string) *Ctx

ContentType sets the response's HTTP content type.

Parameters:

  • mime (string): The content type to set.

Returns:

  • *Ctx: The current HTTP context.

func (*Ctx) DeleteParam added in v1.17.0

func (c *Ctx) DeleteParam(key string, paramType ...string) IRequestData

DeleteParam deletes a parameter from the request.

Parameters:

  • key (string): The key of the parameter to delete.
  • paramType (...string): Optional parameter type. Can be ParamTypePost or ParamTypeQuery or ParamTypeBody. Default is both.

Returns:

  • IRequestData: The current request data interface for chaining.

func (*Ctx) Download

func (c *Ctx) Download(file string, filename ...string) error

Download transfers the file from the provided path as an attachment. Typically, browsers will prompt the user to download the file. By default, the Content-Disposition header's filename parameter is set to the provided file path's basename. Optionally, this behavior can be overridden with a custom filename.

Parameters:

  • file (string): The path of the file to download.
  • filename (...string): Optional custom filename for the Content-Disposition header.

Returns:

  • error: An error if the file transfer fails, otherwise nil.

func (*Ctx) Error

func (c *Ctx) Error(data any, httpCode ...int) error

Error sends an error JSON response with a specific HTTP status code.

Parameters:

  • data (any): The data to include in the JSON response.
  • httpCode (...int): Optional HTTP status code to set (default: 400 Bad Request).

Returns:

  • error: An error if the response generation fails, otherwise nil.

func (*Ctx) File

func (c *Ctx) File(file string, compress ...bool) error

File transfers the file from the given path.

The file is not compressed by default, enable this option by passing 'true' as an argument.

Parameters:

  • file (string): The path of the file to be transferred.
  • compress (...bool): Optional argument to enable compression. Default is 'false'. Pass 'true' to enable.

Returns:

  • error: An error if the file transfer fails, otherwise nil.

Behavior:

  • Automatically sets the Content-Type response HTTP header field based on the file's extension.
  • If the file path is relative, it converts it to an absolute path.
  • Handles errors when file paths are invalid or if the file is not found.
  • Configures HTTP headers for compression if explicitly enabled.

func (*Ctx) FormBool

func (c *Ctx) FormBool(key string) (bool, error)

FormBool retrieves the boolean value of a form key from a POST or PUT request.

Parameters:

  • key (string): The key to retrieve from the form data.

Returns:

  • bool: The boolean value associated with the provided key.
  • error: An error if the value cannot be converted to a boolean.

func (*Ctx) FormFloat

func (c *Ctx) FormFloat(key string) (float64, error)

FormFloat retrieves the float value of a form key from a POST or PUT request.

Parameters:

  • key (string): The key to retrieve from the form data.

Returns:

  • float64: The float value associated with the provided key.
  • error: An error if the value cannot be converted to a float.

func (*Ctx) FormInt

func (c *Ctx) FormInt(key string) (int, error)

FormInt retrieves the integer value of a form key from a POST or PUT request.

Parameters:

  • key (string): The key to retrieve from the form data.

Returns:

  • int: The integer value associated with the provided key.
  • error: An error if the value cannot be converted to an integer.

func (*Ctx) FormStr added in v1.15.5

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

FormStr retrieves the string value of a form key from a POST or PUT request.

Parameters:

  • key (string): The key to retrieve from the form data.

Returns:

  • string: The string value associated with the provided key.

func (*Ctx) FormUpload

func (c *Ctx) FormUpload(files ...string) ([]UploadedFile, error)

FormUpload processes and retrieves uploaded files from a POST or PUT request.

Parameters:

  • files (...string): Optional list of form field names to process. If none are specified, all uploaded files are processed.

Returns:

  • []UploadedFile: A list of UploadedFile details for each processed file.
  • error: An error if the file upload processing fails.

func (*Ctx) FormVal

func (c *Ctx) FormVal(key string) []byte

FormVal retrieves the value of a form key from a POST PUT request query string or body.

The value is searched in the following places:

  • Query string.
  • POST or PUT body.

There are more fine-grained methods for obtaining form values:

  • QueryArgs for obtaining values from query string.
  • PostArgs for obtaining values from POST or PUT body.
  • MultipartForm for obtaining values from multipart form.
  • FormFile for obtaining uploaded files.

Parameters:

  • key (string): The key to retrieve from the form data.

Returns:

  • []byte: The value associated with the provided key.

func (*Ctx) GetCookie

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

GetCookie retrieves a cookie value from the request's HTTP header.

Parameters:

  • key (string): The name of the cookie.

Returns:

  • string: The value of the cookie; an empty string if not found.

func (*Ctx) GetData

func (c *Ctx) GetData(key string) any

GetData retrieves data from the request context Ctx.

Parameters:

  • key (string): The key associated with the data.

Returns:

  • any: The data associated with the provided key.

func (*Ctx) GetReqHeaders

func (c *Ctx) GetReqHeaders() map[string][]string

GetReqHeaders returns all HTTP request headers.

Returns:

  • map[string][]string: A map of header keys and their respective values.

func (*Ctx) GetSession added in v1.9.0

func (c *Ctx) GetSession(key string) any

GetSession retrieves data from the session context.

Parameters:

  • key (string): The key associated with the session data.

Returns:

  • any: The session data associated with the provided key.

func (*Ctx) HTML

func (c *Ctx) HTML(body string) error

HTML sets the HTTP response body content to the provided HTML string.

Parameters:

  • body (string): The HTML content to send as the response body.

Returns:

  • error: An error if setting the response body fails.

func (*Ctx) JSON

func (c *Ctx) JSON(data any) error

JSON serializes the given data into JSON and sends it as the HTTP response.

Parameters:

  • data (Data): The data to serialize into JSON.

Returns:

  • error: An error if the JSON serialization or sending the response fails.

func (*Ctx) NoContent

func (c *Ctx) NoContent() error

NoContent sends a response with no content.

Returns:

  • error: An error if the response generation fails, otherwise nil.

func (*Ctx) OriginalURL

func (c *Ctx) OriginalURL() string

OriginalURL retrieves the original URL of the HTTP request.

Returns:

  • string: The original URL requested by the client.

func (*Ctx) ParseBody

func (c *Ctx) ParseBody(data any) error

ParseBody parses the HTTP request body into the provided struct.

Parameters:

  • data (any): A pointer to a struct where the body data will be unmarshalled.

Returns:

  • error: An error if parsing fails, otherwise nil.

func (*Ctx) ParseQuery

func (c *Ctx) ParseQuery(data *Data) error

ParseQuery parses the query string into the provided struct.

Parameters:

  • out (any): A pointer to a struct where the query data will be unmarshalled.

Returns:

  • error: Always returns nil (currently not implemented).

func (*Ctx) Path

func (c *Ctx) Path() string

Path retrieves the URI path of the current request.

Returns:

  • string: The URI path as a string.

func (*Ctx) PathVal

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

PathVal retrieves a value from the path parameters of the HTTP request.

Parameters:

  • key (string): The name of the path parameter to retrieve.

Returns:

  • string: The value associated with the provided key, or an empty string if the key is not found.

func (*Ctx) PostBool added in v1.17.0

func (c *Ctx) PostBool(key string) (bool, error)

PostBool retrieves a boolean value from the POST request data.

Parameters:

  • key (string): The key to retrieve from POST data.

Returns:

  • bool: The boolean value associated with the provided key.
  • error: An error if key not found or value cannot be converted to boolean.

func (*Ctx) PostFloat added in v1.17.0

func (c *Ctx) PostFloat(key string) (float64, error)

PostFloat retrieves a float value from the POST request data.

Parameters:

  • key (string): The key to retrieve from POST data.

Returns:

  • float64: The float value associated with the provided key.
  • error: An error if key not found or value cannot be converted to float.

func (*Ctx) PostInt added in v1.17.0

func (c *Ctx) PostInt(key string) (int, error)

PostInt retrieves an integer value from the POST request data.

Parameters:

  • key (string): The key to retrieve from POST data.

Returns:

  • int: The integer value associated with the provided key.
  • error: An error if key not found or value cannot be converted to integer.

func (*Ctx) PostStr added in v1.17.0

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

PostStr retrieves a string value from the POST request data.

Parameters:

  • key (string): The key to retrieve from POST data.

Returns:

  • string: The string value associated with the provided key, or empty string if not found.

func (*Ctx) Posts added in v1.17.0

func (c *Ctx) Posts() map[string][]byte

Posts retrieves all key-value pairs from the POST of the HTTP request.

Returns:

  • map[string]string: A map of key-value pairs representing the query string data.

func (*Ctx) Queries

func (c *Ctx) Queries() map[string]string

Queries retrieves all key-value pairs from the query string of the HTTP request.

Returns:

  • map[string]string: A map of key-value pairs representing the query string data.

func (*Ctx) QueryBool

func (c *Ctx) QueryBool(key string) (bool, error)

QueryBool retrieves a boolean value from the query string or form data of the HTTP request.

Parameters:

  • key (string): The key to retrieve the boolean value from.

Returns:

  • bool: The boolean value associated with the provided key.
  • error: An error if the value cannot be converted to a boolean.

func (*Ctx) QueryFloat

func (c *Ctx) QueryFloat(key string) (float64, error)

QueryFloat retrieves a float value from the query string or form data of the HTTP request.

Parameters:

  • key (string): The key to retrieve the float value from.

Returns:

  • float64: The float value associated with the provided key.
  • error: An error if the value cannot be converted to a float.

func (*Ctx) QueryInt

func (c *Ctx) QueryInt(key string) (int, error)

QueryInt retrieves an integer value from the query string of the HTTP request.

Parameters:

  • key (string): The key to retrieve from the query string.

Returns:

  • int: The integer value associated with the provided key.
  • error: An error if the value cannot be converted to an integer.

func (*Ctx) QueryStr

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

QueryStr retrieves a string value from the query string of the HTTP request.

Parameters:

  • key (string): The key to retrieve from the query string.

Returns:

  • string: The value associated with the provided key.

func (*Ctx) Raw

func (c *Ctx) Raw(body []byte) error

Raw sets the HTTP response body directly using the given raw byte slice.

Parameters:

  • body ([]byte): The raw byte slice to send as the response body.

Returns:

  • error: An error if setting the response body fails.

func (*Ctx) Redirect

func (c *Ctx) Redirect(path string) error

Redirect sends a redirect response to the specified path.

Parameters:

  • path (string): The URL path or full URL to redirect to.

Returns:

  • error: An error if setting the redirect fails.

func (*Ctx) Root

func (c *Ctx) Root() *fasthttp.RequestCtx

Root returns the original HTTP request context from fasthttp.

Returns:

  • *fasthttp.RequestCtx: The root HTTP request context.

func (*Ctx) Router

func (c *Ctx) Router() *Router

Router returns the original router associated with the context.

Returns:

  • *Router: The router instance associated with the current request context.

func (*Ctx) SetCookie

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

SetCookie sets a cookie in the response's HTTP header.

Parameters:

  • key (string): The cookie name.
  • value (string): The cookie value.

Returns:

  • *Ctx: The current HTTP context.

func (*Ctx) SetData

func (c *Ctx) SetData(key string, data any)

SetData stores data in the request context Ctx.

Parameters:

  • key (string): The key under which the data will be stored.
  • data (any): The data to be stored.

func (*Ctx) SetHeader

func (c *Ctx) SetHeader(key, val string) *Ctx

SetHeader sets the response's HTTP header field with the specified key and value.

Parameters:

  • key (string): The header key.
  • val (string): The header value.

Returns:

  • *Ctx: The current HTTP context.

func (*Ctx) SetSession added in v1.9.0

func (c *Ctx) SetSession(key string, data any)

SetSession stores data in the session context.

Parameters:

  • key (string): The key under which the session data will be stored.
  • data (any): The session data to be stored.

func (*Ctx) Status

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

Status sets the response's HTTP status code.

Parameters:

  • code (int): The HTTP status code to set.

Returns:

  • *Ctx: The current HTTP context.

func (*Ctx) Stream

func (c *Ctx) Stream(stream io.Reader, size ...int) error

Stream sets the HTTP response body to a data stream with an optional size.

Parameters:

  • stream (io.Reader): The data stream to send as the response body.
  • size (...int): Optional argument to specify the size of the stream body. Defaults to -1 (unknown size).

Returns:

  • error: An error if setting the response body stream fails.

func (*Ctx) String

func (c *Ctx) String(body string) error

String sets the HTTP response body content to the provided plain text string.

Parameters:

  • body (string): The plain text content to send as the response body.

Returns:

  • error: An error if setting the response body fails.

func (*Ctx) Success

func (c *Ctx) Success(data any) error

Success sends a successful JSON response.

Parameters:

  • data (any): The data to include in the JSON response.

Returns:

  • error: An error if the response generation fails, otherwise nil.

func (*Ctx) View

func (c *Ctx) View(template string, data Data) error

View renders a template file and sends the resulting HTML as the HTTP response.

Parameters:

  • template (string): The name or path of the template file to render.
  • data (Data): The data to pass into the template for rendering.

Returns:

  • error: An error if the template rendering or sending the response fails.

type Data

type Data Map

Data generic map type for almost usage purpose. It is used as an alias for the Map type.

func (Data) Delete added in v1.15.0

func (d Data) Delete(key string) Data

Delete removes the given key and its associated value from the Data. Returns the modified Data. If the key does not exist, no action is taken.

func (Data) Get added in v1.15.0

func (d Data) Get(key string) any

Get returns the value associated with the given key. If the key does not exist, it returns nil.

func (Data) GetBool added in v1.15.0

func (d Data) GetBool(key string) bool

GetBool returns the boolean value associated with the given key. Returns false if the key does not exist or value is not a boolean.

func (Data) GetData added in v1.15.0

func (d Data) GetData(key string) Data

GetData returns the Data value associated with the given key. Returns nil if the key does not exist or value is not of type Data.

func (Data) GetFloat added in v1.15.0

func (d Data) GetFloat(key string) float64

GetFloat returns the float64 value associated with the given key. It attempts to convert various numeric types to float64. Returns 0 if the key does not exist or value cannot be converted to float64.

func (Data) GetInt added in v1.15.0

func (d Data) GetInt(key string) int

GetInt returns the integer value associated with the given key. It attempts to convert various numeric types to int. Returns 0 if the key does not exist or value cannot be converted to int.

func (Data) GetString added in v1.15.0

func (d Data) GetString(key string) string

GetString returns the string value associated with the given key. Returns empty string if the key does not exist or value is not a string.

func (Data) Has added in v1.15.0

func (d Data) Has(key string) bool

Has checks if the given key exists in the Data. Returns true if the key exists, false otherwise.

func (Data) Keys added in v1.15.0

func (d Data) Keys() []string

func (Data) Set added in v1.15.0

func (d Data) Set(key string, value any) Data

Set sets the value for the given key and returns the modified Data. If the key already exists, its value will be overwritten.

func (Data) Vals added in v1.15.0

func (d Data) Vals() []any

type DefaultSession added in v1.9.0

type DefaultSession struct {
}

func (*DefaultSession) Get added in v1.9.0

func (v *DefaultSession) Get(c *Ctx, key string) any

Get retrieves a value from the session associated with the given key. Parameters:

  • c: The context object used to manage session information.
  • key: The key associated with the value to retrieve.

Returns:

The value stored in the session, or nil if not found.

func (*DefaultSession) Set added in v1.9.0

func (v *DefaultSession) Set(c *Ctx, key string, value any)

Set stores a value in the session associated with the given key. Parameters:

  • c: The context object used to manage session information.
  • key: The key to associate with the value.
  • value: The value to store in the session.

type DefaultView added in v1.8.0

type DefaultView struct {
}

DefaultView is a fallback view engine that panics when methods are called. It ensures that an appropriate view engine is registered to avoid runtime errors.

func (*DefaultView) Parse added in v1.8.0

func (v *DefaultView) Parse(tpl string, data Data) string

Parse parses the given template `tpl` with the provided data `data` and returns the resulting string. In the case of DefaultView, it panics with the error message `viewError` because no view engine is registered.

Parameters:

  • tpl: The template string to be parsed.
  • data: The data to be injected into the template.

Returns:

  • A string representation of the rendered template.

Note: This function always panics with `viewError` for the DefaultView implementation.

func (*DefaultView) Writer added in v1.8.0

func (v *DefaultView) Writer(tpl string, data Data, writer io.Writer) error

Writer panics with viewError when called, indicating no view engine is registered.

Parameters:

  • tpl: The template string to be written.
  • data: The data to be injected into the template.
  • writer: The io.Writer where the rendered content is written.

Returns:

  • Always panics with `viewError` for DefaultView implementation.

type Endpoint

type Endpoint struct{}

Endpoint Default handler.

Implements:

  • Validate: A no-op validation method.
  • Handle: A no-op handling method.

func (*Endpoint) Handle

func (e *Endpoint) Handle(c *Ctx) error

Handle handles the request context.

Parameters:

  • c (*Ctx): The current HTTP request context.

Returns:

  • error: Always nil (no handling logic implemented).

func (*Endpoint) Validate

func (e *Endpoint) Validate(c *Ctx) error

Validate validates the request context.

Parameters:

  • c (*Ctx): The current HTTP request context.

Returns:

  • error: Always nil (no validation logic implemented).

type FnHookMiddleware

type FnHookMiddleware func(fly IFlyMiddleware)

FnHookMiddleware Function type for registering middleware hooks. Parameters:

  • fly: An instance of IFlyMiddleware used for middleware setup.

type FnHookRoute

type FnHookRoute func(fly IFly)

FnHookRoute Function type for registering route hooks. Parameters:

  • fly: An instance of IFly used for route setup.

type GFly

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

GFly Struct defining main elements in the application.

func (*GFly) Apply added in v1.15.3

func (fly *GFly) Apply(middlewares ...MiddlewareHandler) func(IHandler) IHandler

Apply creates an Interceptor chain handler for a specific handler.

Example usage:

group.POST("/one", group.Apply(middleware.RuleMiddlewareFunc)(api.NewDefaultApi()))

Parameters:

  • middlewares ([]MiddlewareHandler): Middleware handlers to be grouped.

Returns:

  • func(IHandler) IHandler: A function that applies the interceptor handlers to an IHandler.

func (*GFly) CONNECT

func (fly *GFly) CONNECT(path string, handler IHandler)

CONNECT is a shortcut for Router.CONNECT(path, handler). Parameters:

  • path (string): The URL path to route the CONNECT request.
  • handler (IHandler): The handler to process the CONNECT request.

func (*GFly) DELETE

func (fly *GFly) DELETE(path string, handler IHandler)

DELETE is a shortcut for Router.DELETE(path, handler). Parameters:

  • path (string): The URL path to route the DELETE request.
  • handler (IHandler): The handler to process the DELETE request.

func (*GFly) GET

func (fly *GFly) GET(path string, handler IHandler)

GET is a shortcut for Router.GET(path, handler). Parameters:

  • path (string): The URL path to route the GET request.
  • handler (IHandler): The handler to process the GET request.

func (*GFly) Group

func (fly *GFly) Group(path string, groupFunc func(*Group))

Group creates a group Handler functions. Parameters:

  • path (string): The URL path prefix for the group.
  • groupFunc (func(*Group)): A function defining routes and middleware for the group.

func (*GFly) HEAD

func (fly *GFly) HEAD(path string, handler IHandler)

HEAD is a shortcut for Router.HEAD(path, handler). Parameters:

  • path (string): The URL path to route the HEAD request.
  • handler (IHandler): The handler to process the HEAD request.

func (*GFly) OPTIONS

func (fly *GFly) OPTIONS(path string, handler IHandler)

OPTIONS is a shortcut for Router.OPTIONS(path, handler). Parameters:

  • path (string): The URL path to route the OPTIONS request.
  • handler (IHandler): The handler to process the OPTIONS request.

func (*GFly) PATCH

func (fly *GFly) PATCH(path string, handler IHandler)

PATCH is a shortcut for Router.PATCH(path, handler). Parameters:

  • path (string): The URL path to route the PATCH request.
  • handler (IHandler): The handler to process the PATCH request.

func (*GFly) POST

func (fly *GFly) POST(path string, handler IHandler)

POST is a shortcut for Router.POST(path, handler). Parameters:

  • path (string): The URL path to route the POST request.
  • handler (IHandler): The handler to process the POST request.

func (*GFly) PUT

func (fly *GFly) PUT(path string, handler IHandler)

PUT is a shortcut for Router.PUT(path, handler). Parameters:

  • path (string): The URL path to route the PUT request.
  • handler (IHandler): The handler to process the PUT request.

func (*GFly) RegisterMiddleware

func (fly *GFly) RegisterMiddleware(fn ...FnHookMiddleware)

RegisterMiddleware Register middleware hooks to process global middleware. Parameters:

  • fn (variadic FnHookMiddleware): List of middleware hook functions to register globally.

func (*GFly) RegisterRouter

func (fly *GFly) RegisterRouter(fn ...FnHookRoute)

RegisterRouter Register route hooks to define application routes. Parameters:

  • fn (variadic FnHookRoute): List of route hook functions to register globally.

func (*GFly) Router

func (fly *GFly) Router() *Router

Router Retrieves the root router in the gFly application. Returns:

  • *Router: The root router instance of the application.

func (*GFly) Run

func (fly *GFly) Run()

Run Start gFly app.

func (*GFly) TRACE

func (fly *GFly) TRACE(path string, handler IHandler)

TRACE is a shortcut for Router.TRACE(path, handler). Parameters:

  • path (string): The URL path to route the TRACE request.
  • handler (IHandler): The handler to process the TRACE request.

func (*GFly) Use

func (fly *GFly) Use(middlewares ...MiddlewareHandler)

Use adds middleware for global (all requests).

Example usage:

group.Use(middleware.RuleMiddlewareFunc, middleware.AuthMiddlewareFunc)

Parameters:

  • middlewares ([]MiddlewareHandler): One or more middleware handlers to be added globally.

type Group

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

Group is a sub-router to group paths

func (*Group) CONNECT

func (g *Group) CONNECT(path string, handler IHandler)

CONNECT is a shortcut for Router.CONNECT(path, handler). Parameters: - path: The path for the CONNECT route. - handler: The handler implementing the IHandler interface to process the HTTP CONNECT request.

func (*Group) DELETE

func (g *Group) DELETE(path string, handler IHandler)

DELETE is a shortcut for Router.DELETE(path, handler). Parameters: - path: The path for the DELETE route. - handler: The handler implementing the IHandler interface to process the HTTP DELETE request.

func (*Group) GET

func (g *Group) GET(path string, handler IHandler)

GET is a shortcut for Router.GET(path, handler). Parameters: - path: The path for the GET route. - handler: The handler implementing the IHandler interface to process the HTTP GET request.

func (*Group) Group

func (g *Group) Group(path string, groupFunc func(*Group))

Group creates a new sub-group of routes with a common path prefix. Parameters: - path: The prefix path for the group. - groupFunc: A function that defines the routes and sub-groups within this group.

func (*Group) HEAD

func (g *Group) HEAD(path string, handler IHandler)

HEAD is a shortcut for Router.HEAD(path, handler). Parameters: - path: The path for the HEAD route. - handler: The handler implementing the IHandler interface to process the HTTP HEAD request.

func (*Group) OPTIONS

func (g *Group) OPTIONS(path string, handler IHandler)

OPTIONS is a shortcut for Router.OPTIONS(path, handler). Parameters: - path: The path for the OPTIONS route. - handler: The handler implementing the IHandler interface to process the HTTP OPTIONS request.

func (*Group) PATCH

func (g *Group) PATCH(path string, handler IHandler)

PATCH is a shortcut for Router.PATCH(path, handler). Parameters: - path: The path for the PATCH route. - handler: The handler implementing the IHandler interface to process the HTTP PATCH request.

func (*Group) POST

func (g *Group) POST(path string, handler IHandler)

POST is a shortcut for Router.POST(path, handler). Parameters: - path: The path for the POST route. - handler: The handler implementing the IHandler interface to process the HTTP POST request.

func (*Group) PUT

func (g *Group) PUT(path string, handler IHandler)

PUT is a shortcut for Router.PUT(path, handler). Parameters: - path: The path for the PUT route. - handler: The handler implementing the IHandler interface to process the HTTP PUT request.

func (*Group) TRACE

func (g *Group) TRACE(path string, handler IHandler)

TRACE is a shortcut for Router.TRACE(path, handler). Parameters: - path: The path for the TRACE route. - handler: The handler implementing the IHandler interface to process the HTTP TRACE request.

func (*Group) Use

func (g *Group) Use(middlewares ...MiddlewareHandler)

Use applies middleware for all router groups. This function appends the provided middleware handlers to the group's middleware chain. Parameters: - middlewares: Variadic parameter accepting one or more middleware handlers of type MiddlewareHandler.

type IData

type IData interface {
	// SetData stores data in the request context Ctx.
	//
	// Parameters:
	//   - key (string): The key under which the data will be stored.
	//   - data (any): The data to be stored.
	SetData(key string, data any)

	// GetData retrieves data from the request context Ctx.
	//
	// Parameters:
	//   - key (string): The key associated with the data.
	//
	// Returns:
	//   - any: The data associated with the provided key.
	GetData(key string) any

	// SetSession stores data in the session context.
	//
	// Parameters:
	//   - key (string): The key under which the session data will be stored.
	//   - data (any): The session data to be stored.
	SetSession(key string, data any)

	// GetSession retrieves data from the session context.
	//
	// Parameters:
	//   - key (string): The key associated with the session data.
	//
	// Returns:
	//   - any: The session data associated with the provided key.
	GetSession(key string) any
}

type IFly

type IFly interface {
	// Run Starts the application.
	Run()

	// Router Gets the web router instance.
	// Returns:
	//   - *Router: The root router instance.
	Router() *Router

	// RegisterMiddleware Registers middleware hooks.
	// Parameters:
	//   - fn: Variadic parameter of FnHookMiddleware functions to set up global middleware.
	RegisterMiddleware(fn ...FnHookMiddleware)

	// RegisterRouter Registers route hooks.
	// Parameters:
	//   - fn: Variadic parameter of FnHookRoute functions to set up application routes.
	RegisterRouter(fn ...FnHookRoute)

	IFlyRouter
	IFlyMiddleware
}

IFly Interface to declare all methods for gFly struct.

func New

func New(config ...Config) IFly

New Create a new gFly application instance. Parameters:

  • config (variadic Config): Optional application configuration(s) for overriding defaults.

Returns:

  • IFly: Instance of gFly application.

type IFlyMiddleware

type IFlyMiddleware interface {
	// Use adds middleware for global (all requests).
	//
	// Parameters:
	//   - middlewares ([]MiddlewareHandler): One or more middleware handlers to be applied globally.
	Use(middlewares ...MiddlewareHandler)

	// Apply creates an Interceptor chain handler for a specific handler.
	//
	// Note: Interceptors have access to response/request before and after the route handler is called
	//
	// Parameters:
	//   - middleware ([]MiddlewareHandler): Middleware handlers to be grouped.
	//
	// Returns:
	//   - func(IHandler) IHandler: A function that applies the interceptor handlers to an IHandler.
	Apply(middleware ...MiddlewareHandler) func(IHandler) IHandler
}

IFlyMiddleware Interface to declare all Middleware methods for gFly struct.

type IFlyRouter

type IFlyRouter interface {
	// GET Http GET method
	// Parameters:
	//   - path (string): The URL path to route the GET request.
	//   - handler (IHandler): The handler to process the GET request.
	GET(path string, handler IHandler)

	// HEAD Http HEAD method
	// Parameters:
	//   - path (string): The URL path to route the HEAD request.
	//   - handler (IHandler): The handler to process the HEAD request.
	HEAD(path string, handler IHandler)

	// POST Http POST method
	// Parameters:
	//   - path (string): The URL path to route the POST request.
	//   - handler (IHandler): The handler to process the POST request.
	POST(path string, handler IHandler)

	// PUT Http PUT method
	// Parameters:
	//   - path (string): The URL path to route the PUT request.
	//   - handler (IHandler): The handler to process the PUT request.
	PUT(path string, handler IHandler)

	// PATCH Http PATCH method
	// Parameters:
	//   - path (string): The URL path to route the PATCH request.
	//   - handler (IHandler): The handler to process the PATCH request.
	PATCH(path string, handler IHandler)

	// DELETE Http DELETE method
	// Parameters:
	//   - path (string): The URL path to route the DELETE request.
	//   - handler (IHandler): The handler to process the DELETE request.
	DELETE(path string, handler IHandler)

	// CONNECT Http CONNECT method
	// Parameters:
	//   - path (string): The URL path to route the CONNECT request.
	//   - handler (IHandler): The handler to process the CONNECT request.
	CONNECT(path string, handler IHandler)

	// OPTIONS Http OPTIONS method
	// Parameters:
	//   - path (string): The URL path to route the OPTIONS request.
	//   - handler (IHandler): The handler to process the OPTIONS request.
	OPTIONS(path string, handler IHandler)

	// TRACE Http TRACE method
	// Parameters:
	//   - path (string): The URL path to route the TRACE request.
	//   - handler (IHandler): The handler to process the TRACE request.
	TRACE(path string, handler IHandler)

	// Group multi routers
	// Parameters:
	//   - path (string): The URL path prefix for the group.
	//   - groupFunc (func(*Group)): A function defining routes and middleware for the group.
	Group(path string, groupFunc func(*Group))
}

IFlyRouter Interface to declare all HTTP methods for gFly struct.

type IGroupMiddleware

type IGroupMiddleware interface {
	// Use applies middleware for all router groups.
	// Important: This should be called at the top of the group router before defining routes.
	// Parameters:
	// - middlewares: Variadic parameter accepting one or more middleware handlers of type MiddlewareHandler.
	Use(middlewares ...MiddlewareHandler)
}

IGroupMiddleware Interface to declare all Middleware methods for gFly struct.

type IGroupRouter

type IGroupRouter interface {
	// GET Http GET method
	// Parameters:
	// - path: The path for the route.
	// - handler: The handler implementing the IHandler interface to process the HTTP GET request.
	GET(path string, handler IHandler)

	// HEAD Http HEAD method
	// Parameters:
	// - path: The path for the route.
	// - handler: The handler implementing the IHandler interface to process the HTTP HEAD request.
	HEAD(path string, handler IHandler)

	// POST Http POST method
	// Parameters:
	// - path: The path for the route.
	// - handler: The handler implementing the IHandler interface to process the HTTP POST request.
	POST(path string, handler IHandler)

	// PUT Http PUT method
	// Parameters:
	// - path: The path for the route.
	// - handler: The handler implementing the IHandler interface to process the HTTP PUT request.
	PUT(path string, handler IHandler)

	// PATCH Http PATCH method
	// Parameters:
	// - path: The path for the route.
	// - handler: The handler implementing the IHandler interface to process the HTTP PATCH request.
	PATCH(path string, handler IHandler)

	// DELETE Http DELETE method
	// Parameters:
	// - path: The path for the route.
	// - handler: The handler implementing the IHandler interface to process the HTTP DELETE request.
	DELETE(path string, handler IHandler)

	// CONNECT Http CONNECT method
	// Parameters:
	// - path: The path for the route.
	// - handler: The handler implementing the IHandler interface to process the HTTP CONNECT request.
	CONNECT(path string, handler IHandler)

	// OPTIONS Http OPTIONS method
	// Parameters:
	// - path: The path for the route.
	// - handler: The handler implementing the IHandler interface to process the HTTP OPTIONS request.
	OPTIONS(path string, handler IHandler)

	// TRACE Http TRACE method
	// Parameters:
	// - path: The path for the route.
	// - handler: The handler implementing the IHandler interface to process the HTTP TRACE request.
	TRACE(path string, handler IHandler)

	// Group multi routers
	// Parameters:
	// - path: The prefix path for the group.
	// - groupFunc: A function that defines the routes and sub-groups in this group.
	Group(path string, groupFunc func(*Group))
}

IGroupRouter Interface to declare all HTTP methods.

type IHandler

type IHandler interface {
	// Validate validates the request context.
	//
	// Parameters:
	//   - c (*Ctx): The current HTTP request context.
	//
	// Returns:
	//   - error: An error if validation fails, otherwise nil.
	Validate(c *Ctx) error

	// Handle handles the request context.
	//
	// Parameters:
	//   - c (*Ctx): The current HTTP request context.
	//
	// Returns:
	//   - error: An error if handling fails, otherwise nil.
	Handle(c *Ctx) error
}

IHandler Interface for a handler request.

type IHeader

type IHeader interface {
	// Status sets the response's HTTP status code.
	//
	// Parameters:
	//   - code (int): The HTTP status code to set.
	//
	// Returns:
	//   - *Ctx: The current HTTP context.
	Status(code int) *Ctx
	// ContentType sets the response's HTTP content type.
	//
	// Parameters:
	//   - mime (string): The content type to set.
	//
	// Returns:
	//   - *Ctx: The current HTTP context.
	ContentType(mime string) *Ctx
	// SetHeader sets the response's HTTP header field with the specified key and value.
	//
	// Parameters:
	//   - key (string): The header key.
	//   - val (string): The header value.
	//
	// Returns:
	//   - *Ctx: The current HTTP context.
	SetHeader(key, val string) *Ctx
	// SetCookie sets a cookie in the response's HTTP header.
	//
	// Parameters:
	//   - key (string): The cookie name.
	//   - value (string): The cookie value.
	//
	// Returns:
	//   - *Ctx: The current HTTP context.
	SetCookie(key, value string) *Ctx
	// GetCookie retrieves a cookie value from the request's HTTP header.
	//
	// Parameters:
	//   - key (string): The name of the cookie.
	//
	// Returns:
	//   - string: The value of the cookie; an empty string if not found.
	GetCookie(key string) string
	// GetReqHeaders returns all HTTP request headers.
	//
	// Returns:
	//   - map[string][]string: A map of header keys and their respective values.
	GetReqHeaders() map[string][]string
	// Path retrieves the URI path of the current request.
	//
	// Returns:
	//   - string: The URI path as a string.
	Path() string
}

type IMiddleware

type IMiddleware interface {
	// Group groups multiple MiddlewareHandler functions together and returns a function
	// which wraps an IHandler with the middleware functionalities.
	//
	// Parameters:
	//   - middlewares: Variadic parameter accepting multiple MiddlewareHandler functions.
	//
	// Returns:
	//   - A function that takes an IHandler and returns a wrapped IHandler with the applied middlewares.
	Group(middlewares ...MiddlewareHandler) func(IHandler) IHandler
}

IMiddleware Middleware interface defines the contract for grouping middleware functions.

func NewMiddleware

func NewMiddleware() IMiddleware

NewMiddleware creates a new instance of Middleware.

Returns:

  • An object implementing the IMiddleware interface.

type IRequestData

type IRequestData interface {
	// ParseBody parses the HTTP request body into the provided struct.
	//
	// Parameters:
	//   - data (any): A pointer to a struct where the body data will be unmarshalled.
	//
	// Returns:
	//   - error: An error if parsing fails, otherwise nil.
	ParseBody(data any) error

	// ParseQuery parses the query string into the provided struct.
	//
	// Parameters:
	//   - data (any): A pointer to a struct where the query data will be unmarshalled.
	//
	// Returns:
	//   - error: An error if parsing fails, otherwise nil.
	ParseQuery(data *Data) error

	// FormVal retrieves the value of a form key from POST/PUT/Query string or body.
	//
	// The value is searched in the following places:
	//
	//   - Query string.
	//   - POST or PUT body.
	//
	// There are more fine-grained methods for obtaining form values:
	//
	//   - QueryArgs for obtaining values from query string.
	//   - PostArgs for obtaining values from POST or PUT body.
	//   - MultipartForm for obtaining values from multipart form.
	//   - FormFile for obtaining uploaded files.
	//
	// Parameters:
	//   - key (string): The key to retrieve from the form data.
	//
	// Returns:
	//   - []byte: The value associated with the provided key.
	FormVal(key string) []byte

	// FormInt retrieves the integer value of a form key from POST/PUT/Query string or body.
	//
	// The value is searched in the following places:
	//
	//   - Query string.
	//   - POST or PUT body.
	//
	// There are more fine-grained methods for obtaining form values:
	//
	//   - QueryArgs for obtaining values from query string.
	//   - PostArgs for obtaining values from POST or PUT body.
	//   - MultipartForm for obtaining values from multipart form.
	//   - FormFile for obtaining uploaded files.
	//
	// Parameters:
	//   - key (string): The key to retrieve from the form data.
	//
	// Returns:
	//   - int: The integer value associated with the provided key.
	//   - error: An error if the value cannot be converted to an integer.
	FormInt(key string) (int, error)

	// FormStr retrieves the string value of a form key from POST/PUT/Query string or body.
	//
	// The value is searched in the following places:
	//
	//   - Query string.
	//   - POST or PUT body.
	//
	// There are more fine-grained methods for obtaining form values:
	//
	//   - QueryArgs for obtaining values from query string.
	//   - PostArgs for obtaining values from POST or PUT body.
	//   - MultipartForm for obtaining values from multipart form.
	//   - FormFile for obtaining uploaded files.
	//
	// Parameters:
	//   - key (string): The key to retrieve from the form data.
	//
	// Returns:
	//   - string: The string value associated with the provided key.
	FormStr(key string) string

	// FormBool retrieves the boolean value of a form key from POST/PUT/Query string or body.
	//
	// The value is searched in the following places:
	//
	//   - Query string.
	//   - POST or PUT body.
	//
	// There are more fine-grained methods for obtaining form values:
	//
	//   - QueryArgs for obtaining values from query string.
	//   - PostArgs for obtaining values from POST or PUT body.
	//   - MultipartForm for obtaining values from multipart form.
	//   - FormFile for obtaining uploaded files.
	//
	// Parameters:
	//   - key (string): The key to retrieve from the form data.
	//
	// Returns:
	//   - bool: The boolean value associated with the provided key.
	//   - error: An error if the value cannot be converted to a boolean.
	FormBool(key string) (bool, error)

	// FormFloat retrieves the float value of a form key from POST/PUT/Query string or body.
	//
	// The value is searched in the following places:
	//
	//   - Query string.
	//   - POST or PUT body.
	//
	// There are more fine-grained methods for obtaining form values:
	//
	//   - QueryArgs for obtaining values from query string.
	//   - PostArgs for obtaining values from POST or PUT body.
	//   - MultipartForm for obtaining values from multipart form.
	//   - FormFile for obtaining uploaded files.
	//
	// Parameters:
	//   - key (string): The key to retrieve from the form data.
	//
	// Returns:
	//   - float64: The float value associated with the provided key.
	//   - error: An error if the value cannot be converted to a float.
	FormFloat(key string) (float64, error)

	// FormUpload processes and retrieves uploaded files from a POST or PUT request.
	//
	// Parameters:
	//   - files (...string): Optional list of form field names to process. If none are specified, all uploaded files are processed.
	//
	// Returns:
	//   - []UploadedFile: A list of UploadedFile details for each processed file.
	//   - error: An error if the file upload processing fails.
	FormUpload(files ...string) ([]UploadedFile, error)

	// Posts retrieves all key-value pairs from the POST/PUT of the HTTP request.
	//
	// Returns:
	//   - map[string]string: A map of key-value pairs representing the query string data.
	Posts() map[string][]byte

	// PostStr retrieves a string value from the POST/PUT request data.
	//
	// Parameters:
	//   - key (string): The key to retrieve from POST data.
	//
	// Returns:
	//   - string: The string value associated with the provided key, or empty string if not found.
	PostStr(key string) string

	// PostInt retrieves an integer value from the POST/PUT request data.
	//
	// Parameters:
	//   - key (string): The key to retrieve from POST data.
	//
	// Returns:
	//   - int: The integer value associated with the provided key.
	//   - error: An error if key not found or value cannot be converted to integer.
	PostInt(key string) (int, error)

	// PostBool retrieves a boolean value from the POST/PUT request data.
	//
	// Parameters:
	//   - key (string): The key to retrieve from POST data.
	//
	// Returns:
	//   - bool: The boolean value associated with the provided key.
	//   - error: An error if key not found or value cannot be converted to boolean.
	PostBool(key string) (bool, error)

	// PostFloat retrieves a float value from the POST/PUT request data.
	//
	// Parameters:
	//   - key (string): The key to retrieve from POST data.
	//
	// Returns:
	//   - float64: The float value associated with the provided key.
	//   - error: An error if key not found or value cannot be converted to float.
	PostFloat(key string) (float64, error)

	// Queries retrieves all key-value pairs from the query string of the HTTP request.
	//
	// Returns:
	//   - map[string]string: A map of key-value pairs representing the query string data.
	Queries() map[string]string

	// QueryStr retrieves a string value from the query string of the HTTP request.
	//
	// Parameters:
	//   - key (string): The key to retrieve from the query string.
	//
	// Returns:
	//   - string: The value associated with the provided key.
	QueryStr(key string) string

	// QueryInt retrieves an integer value from the query string of the HTTP request.
	//
	// Parameters:
	//   - key (string): The key to retrieve from the query string.
	//
	// Returns:
	//   - int: The integer value associated with the provided key.
	//   - error: An error if the value cannot be converted to an integer.
	QueryInt(key string) (int, error)

	// QueryBool retrieves a boolean value from the query string of the HTTP request.
	//
	// Parameters:
	//   - key (string): The key to retrieve from the query string.
	//
	// Returns:
	//   - bool: The boolean value associated with the provided key.
	//   - error: An error if the value cannot be converted to a boolean.
	QueryBool(key string) (bool, error)

	// QueryFloat retrieves a float value from the query string of the HTTP request.
	//
	// Parameters:
	//   - key (string): The key to retrieve from the query string.
	//
	// Returns:
	//   - float64: The float value associated with the provided key.
	//   - error: An error if the value cannot be converted to a float.
	QueryFloat(key string) (float64, error)

	// PathVal retrieves a value from the path parameters of the HTTP request.
	//
	// Parameters:
	//   - key (string): The name of the path parameter to retrieve.
	//
	// Returns:
	//   - string: The value associated with the provided key.
	PathVal(key string) string

	// OriginalURL retrieves the original URL of the HTTP request.
	//
	// Returns:
	//   - string: The original URL requested by the client.
	OriginalURL() string

	// AddParam adds a parameter to the request.
	//
	// Parameters:
	//   - key (string): The key of the parameter to add.
	//   - value (string): The value to associate with the key.
	//   - paramType (...string): Optional parameter type. Can be "form" or "query". Default is both.
	//
	// Returns:
	//   - IRequestData: The current request data interface for chaining.
	AddParam(key string, value string, paramType ...string) IRequestData

	// DeleteParam deletes a parameter from the request.
	//
	// Parameters:
	//   - key (string): The key of the parameter to delete.
	//   - paramType (...string): Optional parameter type. Can be "form" or "query". Default is both.
	//
	// Returns:
	//   - IRequestData: The current request data interface for chaining.
	DeleteParam(key string, paramType ...string) IRequestData
}

IRequestData provides an interface for handling HTTP request data, such as form values, queries, and uploaded files, as well as parsing body content into specific data structures.

type IResponse

type IResponse interface {
	// Success sends a successful JSON response.
	//
	// Parameters:
	//   - data (any): The data to include in the JSON response.
	//
	// Returns:
	//   - error: An error if the response generation fails, otherwise nil.
	Success(data any) error

	// Error sends an error JSON response.
	//
	// Parameters:
	//   - data (any): The data to include in the JSON response.
	//   - httpCode (...int): Optional HTTP status code to set (default: 400 Bad Request).
	//
	// Returns:
	//   - error: An error if the response generation fails, otherwise nil.
	Error(data any, httpCode ...int) error

	// NoContent sends a response with no content.
	//
	// Returns:
	//   - error: An error if the response generation fails, otherwise nil.
	NoContent() error

	// View renders and sends a template page response.
	//
	// Parameters:
	//   - template (string): The name or path of the template to render.
	//   - data (Data): The data to inject into the template.
	//
	// Returns:
	//   - error: An error if template rendering or response generation fails, otherwise nil.
	View(template string, data Data) error

	// JSON sends a JSON response.
	//
	// Parameters:
	//   - data (Data): The data to include in the JSON response.
	//
	// Returns:
	//   - error: An error if the response generation fails, otherwise nil.
	JSON(data Data) error

	// HTML sends an HTML response.
	//
	// Parameters:
	//   - body (string): The HTML content to include in the response.
	//
	// Returns:
	//   - error: An error if the response generation fails, otherwise nil.
	HTML(body string) error

	// String sends a plain text response.
	//
	// Parameters:
	//   - body (string): The plain text content to include in the response.
	//
	// Returns:
	//   - error: An error if the response generation fails, otherwise nil.
	String(body string) error

	// Raw sends a raw byte response.
	//
	// Parameters:
	//   - body ([]byte): The raw byte content to include in the response.
	//
	// Returns:
	//   - error: An error if the response generation fails, otherwise nil.
	Raw(body []byte) error

	// Stream sends a streaming response.
	//
	// Parameters:
	//   - stream (io.Reader): The data stream to send in the response.
	//   - size (...int): Optional body size for the stream (default: -1 for unknown size).
	//
	// Returns:
	//   - error: An error if the response generation fails, otherwise nil.
	Stream(stream io.Reader, size ...int) error

	// Redirect sends a redirect response.
	//
	// Parameters:
	//   - path (string): The URL path or full URL to redirect to.
	//
	// Returns:
	//   - error: An error if the redirect fails, otherwise nil.
	Redirect(path string) error

	// Download sends a file as an attachment.
	//
	// Parameters:
	//   - file (string): The path of the file to send.
	//   - filename (...string): Optional custom filename for the attachment.
	//
	// Returns:
	//   - error: An error if the file transfer fails, otherwise nil.
	Download(file string, filename ...string) error

	// File sends a file as a response.
	//
	// Parameters:
	//   - file (string): The path of the file to send.
	//   - compress (...bool): Optional compression flag (default: false).
	//
	// Returns:
	//   - error: An error if the file transfer fails, otherwise nil.
	File(file string, compress ...bool) error
}

type ISession added in v1.9.0

type ISession interface {
	// Set stores a value in the session associated with the given key.
	// Parameters:
	//  - c: The context object used to manage session information.
	//  - key: The key to associate with the value.
	//  - value: The value to store in the session.
	Set(c *Ctx, key string, value any)

	// Get retrieves a value from the session associated with the given key.
	// Parameters:
	//  - c: The context object used to manage session information.
	//  - key: The key associated with the value to retrieve.
	// Returns:
	//  The value stored in the session, or nil if not found.
	Get(c *Ctx, key string) any
}

type IView added in v1.8.0

type IView interface {
	// Parse builds a string from the template `tpl` and the provided data `data`.
	//
	// Parameters:
	//   - tpl: The template string to be rendered.
	//   - data: A Data map containing key-value pairs to be injected into the template.
	//
	// Returns:
	//   - A string representation of the rendered template.
	Parse(tpl string, data Data) string

	// Writer writes the rendered content of template `tpl` and data `data`
	// to the provided io.Writer `writer`.
	//
	// Parameters:
	//   - tpl: The template string to be rendered.
	//   - data: A Data map containing key-value pairs to be injected into the template.
	//   - writer: An io.Writer where the rendered content will be written.
	//
	// Returns:
	//   - An error if writing to the writer fails, otherwise nil.
	Writer(tpl string, data Data, writer io.Writer) error
}

IView defines the interface for a view engine that can parse templates into strings or write the rendered content directly to an io.Writer.

type Map

type Map map[string]any

Map generic map type for almost usage purpose. It is shorthand for a map with string keys and values of any type.

type Middleware

type Middleware struct{}

Middleware represents a struct implementing the IMiddleware interface.

func (*Middleware) Group

func (m *Middleware) Group(middlewares ...MiddlewareHandler) func(IHandler) IHandler

Group Create a group of Middleware functions. Implements the Group method for the IMiddleware interface.

Parameters:

  • middlewares: Variadic parameter accepting multiple MiddlewareHandler functions.

Returns:

  • A function that takes an IHandler and returns a wrapped IHandler with the applied middlewares.

type MiddlewareHandler

type MiddlewareHandler func(ctx *Ctx) error

MiddlewareHandler must return RequestHandler for continuing or error to stop on it. It is a function type that takes a context object and processes it.

type Page

type Page struct {
	Endpoint
}

Page Abstract web page.

Inherits:

  • Endpoint: Base endpoint for page handling logic.

type RequestHandler

type RequestHandler func(ctx *Ctx) error

RequestHandler A wrapper of fasthttp.RequestHandler.

Parameters:

  • ctx (*Ctx): The current HTTP request context.

Returns:

  • error: An error if the handling fails, otherwise nil.

type Router

type Router struct {

	// SaveMatchedRoutePath, if enabled, adds the matched route path onto
	// the ctx.UserValue context before invoking the handler.
	// The matched route path is only added to handlers of routes registered
	// with this option enabled.
	SaveMatchedRoutePath bool

	// RedirectTrailingSlash 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

	// RedirectFixedPath enables auto-correction of paths if no handler exists for the requested path.
	// 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.
	// Afterward 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

	// HandleMethodNotAllowed, when enabled, checks if a route is reachable
	// with a different HTTP method when the current request method fails.
	// 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

	// HandleOPTIONS automatically handles OPTIONS requests when enabled.
	// Custom OPTIONS handlers take precedence over automatic responses.
	HandleOPTIONS bool

	// GlobalOPTIONS is an optional handler invoked for automatic OPTIONS requests
	// when HandleOPTIONS is true and no specific OPTIONS handler is set.
	// 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 RequestHandler

	// NotFound defines a custom handler for unmatched requests.
	// Configurable RequestHandler which is called when no matching route is
	// found. If it is not set, default NotFound is used.
	NotFound RequestHandler

	// MethodNotAllowed defines a custom handler for requests with unsupported methods
	// Configurable RequestHandler which is called when a request
	// cannot be routed and HandleMethodNotAllowed is true.
	// If it is not set, ctx.Error with fasthttp.StatusMethodNotAllowed is used.
	// The "Allow" header with allowed request methods is set before the handler is called.
	MethodNotAllowed RequestHandler

	// PanicHandler is a function to recover from panics triggered in 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
	// unrecoverable panics.
	PanicHandler func(*Ctx, any)
	// contains filtered or unexported fields
}

Router is a high-performance HTTP request router. It dispatches requests to handlers based on the HTTP method and the requested path. Provides options for path matching, request handling, redirection, and error handling.

func NewRouter

func NewRouter() *Router

NewRouter returns a new instance of the Router struct.

This function initializes a Router with default configurations, including: - Path auto-correction (both trailing slash correction and fixed path correction) enabled. - Automatic handling of OPTIONS requests and checks for allowed methods. - PanicHandler for recovering from panics in HTTP handlers. - GlobalOPTIONS handler to set default CORS headers for OPTIONS requests.

Returns: - *Router: A pointer to the newly created Router instance, with default settings.

func (*Router) CONNECT

func (r *Router) CONNECT(path string, handler IHandler)

CONNECT is a shortcut for router.Handle with the CONNECT HTTP method.

Parameters:

  • path: string — The route path.
  • handler: IHandler — The handler function for the route.

func (*Router) DELETE

func (r *Router) DELETE(path string, handler IHandler)

DELETE is a shortcut for router.Handle with the DELETE HTTP method.

Parameters:

  • path: string — The route path.
  • handler: IHandler — The handler function for the route.

func (*Router) GET

func (r *Router) GET(path string, handler IHandler)

GET is a shortcut for router.Handle with the GET HTTP method.

Parameters:

  • path: string — The route path.
  • handler: IHandler — The handler function for the route.

func (*Router) Group

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

Group creates a new route group with the specified base path.

Route groups are a convenient way to group related routes under a common prefix. All routes registered through the returned group will have their paths automatically prefixed with the group's base path.

The group's base path should not end with a trailing slash, except for the root path ("/"). If the provided path violates this rule, the function will panic.

Parameters:

  • path: string — The base path for the group.

Returns:

  • *Group: A pointer to the newly created route group, with the specified base path.

func (*Router) HEAD

func (r *Router) HEAD(path string, handler IHandler)

HEAD is a shortcut for router.Handle with the HEAD HTTP method.

Parameters:

  • path: string — The route path.
  • handler: IHandler — The handler function for the route.

func (*Router) Handle

func (r *Router) Handle(method, path string, handler IHandler)

Handle registers a new request handler with the given path and method.

This function is intended to register a handler for a specified HTTP method and route path. It provides validation for the method and handler parameters, as well as handling optional routes.

If the HTTP method is empty or the handler is nil, the function will panic. It also handles the creation of internal structures for method-based routing and manages optional route paths (e.g., paths with optional parameters).

Parameters:

  • method: string — The HTTP method (e.g., "GET", "POST", etc.) for which the handler is registered.
  • path: string — The route path that the handler will handle. Must be a valid path.
  • handler: IHandler — The handler interface responsible for processing requests.

Return:

  • No return value. This function registers the specified route and handler.

func (*Router) Handler

func (r *Router) Handler(ctx *Ctx) error

Handler processes incoming HTTP requests and routes them to the appropriate handler. It supports panic recovery, request validation, method-based routing, and error handling.

Parameters:

  • ctx: *Ctx — The context of the current request, containing request and response details.

Returns:

  • error: Returns any error encountered during request handling or validation. If no error occurs, returns nil.

func (*Router) List

func (r *Router) List() map[string][]string

List returns all registered routes grouped by method.

Returns:

  • map[string][]string: A map where the key is the HTTP method and the value is a slice of registered route paths.

func (*Router) Lookup

func (r *Router) Lookup(method, path string, ctx *Ctx) (IHandler, bool)

Lookup retrieves a registered handler for a given HTTP method and route path.

This method is useful for manually inspecting the routing tree, which can be helpful for building frameworks or debugging purposes. It returns the handler function for the provided method and path, if found.

Parameters:

  • method: string — The HTTP method (e.g., "GET", "POST", etc.) for which to perform the lookup.
  • path: string — The route path to look up in the router.
  • ctx: *Ctx — The current request context, potentially providing additional data necessary for handling the request during lookup.

Returns:

  • IHandler: The handler interface for processing requests if the method and path match.
  • bool: Indicates whether a trailing slash redirection should be performed in case of a mismatch.

func (*Router) Mutable

func (r *Router) Mutable(v bool)

Mutable sets whether the routing tree allows updates to the route handlers.

By default, this is disabled, meaning the routing tree is immutable once initialized. Enabling it allows modifications to the route handlers.

WARNING: This feature should be used cautiously, as it may lead to unexpected behaviors in concurrent scenarios.

Parameters:

  • v: bool — A boolean value indicating whether the routing tree should be mutable.

Returns:

  • None

func (*Router) OPTIONS

func (r *Router) OPTIONS(path string, handler IHandler)

OPTIONS is a shortcut for router.Handle with the OPTIONS HTTP method.

Parameters:

  • path: string — The route path.
  • handler: IHandler — The handler function for the route.

func (*Router) PATCH

func (r *Router) PATCH(path string, handler IHandler)

PATCH is a shortcut for router.Handle with the PATCH HTTP method.

Parameters:

  • path: string — The route path.
  • handler: IHandler — The handler function for the route.

func (*Router) POST

func (r *Router) POST(path string, handler IHandler)

POST is a shortcut for router.Handle with the POST HTTP method.

Parameters:

  • path: string — The route path.
  • handler: IHandler — The handler function for the route.

func (*Router) PUT

func (r *Router) PUT(path string, handler IHandler)

PUT is a shortcut for router.Handle with the PUT HTTP method.

Parameters:

  • path: string — The route path.
  • handler: IHandler — The handler function for the route.

func (*Router) ServeFiles

func (r *Router) ServeFiles(path, rootPath string)

ServeFiles serves files from the specified root directory for the given route path.

The route `path` must end with "/{filepath:*}", allowing dynamic file serving based on the requested filepath. Files are served from the local filesystem rooted at the given `rootPath`. For example, if `rootPath` is "/etc" and the requested {filepath:*} is "passwd", the handler serves the file located at "/etc/passwd".

This function sets up a file server using default settings, such as generating index pages and accepting byte ranges when serving files.

Parameters:

  • path: string — The route path where files will be served. Must end with "/{filepath:*}".
  • rootPath: string — The root directory of the file system to serve files from.

Example:

router.ServeFiles("/static/{filepath:*}", "./public")

func (*Router) ServeFilesCustom

func (r *Router) ServeFilesCustom(path string, fs *fasthttp.FS)

ServeFilesCustom serves files from the given file system settings with custom configurations.

This function allows for serving files from a specific file system (`fasthttp.FS`) and provides control over indexing, path rewriting, byte range requests, and other customizations via the `fasthttp.FS` configuration.

The route `path` must end with "/{filepath:*}", enabling dynamic serving of requested file paths. If the route does not conform to this format, it will panic.

If `fs.PathRewrite` is nil and the route `path` contains slashes, the slashes are automatically stripped from the path and used for path rewriting.

Parameters:

  • path: string — The route path where files will be served. Must end with "/{filepath:*}".
  • fs: *fasthttp.FS — The custom file system configuration used to serve files.

Example:

router.ServeFilesCustom("/assets/{filepath:*}", &fasthttp.FS{
	Root:			   "./assets",
	IndexNames:		 []string{"index.html"},
	GenerateIndexPages: false,
	AcceptByteRange:	true,
})

The example above will serve files from the "assets" directory for requests that match the route path "/assets/{filepath:*}".

Return:

No return value. This function registers the route with the router.

func (*Router) TRACE

func (r *Router) TRACE(path string, handler IHandler)

TRACE is a shortcut for router.Handle with the TRACE HTTP method.

Parameters:

  • path: string — The route path.
  • handler: IHandler — The handler function for the route.

type Tree

type Tree struct {

	// If enabled, the node handler could be updated.
	Mutable bool
	// contains filtered or unexported fields
}

Tree is a routes storage, which organizes routing paths in a hierarchical structure.

func NewTree

func NewTree() *Tree

NewTree creates and returns a new instance of a Tree with an initialized root node.

Returns:

  • *Tree: An empty tree structure with a root node of type 'root'.

func (*Tree) Add

func (t *Tree) Add(path string, handler IHandler)

Add adds a node with the specified path and associated handler to the tree. The path must begin with a '/' character, and the handler should not be nil. This function is not safe to call concurrently.

WARNING: Not concurrency-safe!

Parameters:

  • path (string): The path of the node to add. It must start with '/'.
  • handler (IHandler): The handler to associate with the specified path.

Panics:

  • If the path does not begin with a '/' character.
  • If the handler is nil.

Behavior:

  • If the given path already exists in the tree structure and the node can be updated (i.e., t.Mutable is true), the handler will be updated.
  • If conflicts occur or the node can't be updated, the function may panic.

func (*Tree) FindCaseInsensitivePath

func (t *Tree) FindCaseInsensitivePath(path string, fixTrailingSlash bool, buf *bytebufferpool.ByteBuffer) bool

FindCaseInsensitivePath performs a case-insensitive search for the specified path within the tree structure, taking into account optional trailing slash handling.

Parameters:

  • path (string): The path to search for. Case-insensitiveness ensures matches regardless of the path's letter casing.
  • fixTrailingSlash (bool): Determines if trailing slash differences should be corrected during the lookup. If true, finds matches with discrepancies in trailing slashes and adjusts accordingly.
  • buf (*bytebufferpool.ByteBuffer): A buffer used for temporary path modifications during the search process.

Returns:

  • (bool): A boolean indicating whether the path was successfully found:
  • true: The path was found, optionally corrected for case or trailing slashes.
  • false: The path was not found or could not be resolved due to differences.

func (*Tree) Get

func (t *Tree) Get(path string, ctx *Ctx) (IHandler, bool)

Get searches for a handler associated with the given path in the tree structure. It processes the given path to find the appropriate handler and updates the context with the values of parameters or wildcards if they exist. Additionally, it can suggest a trailing slash redirection if applicable.

Parameters:

  • path (string): The path to search for in the tree.
  • ctx (*Ctx): The context to be updated with user values (e.g., parameters or wildcards).

Returns:

  • (IHandler): The handler associated with the given path, or nil if none is found.
  • (bool): A boolean indicating if a trailing slash redirect (TSR) is recommended.

Behavior:

  • If the path matches the root or its child nodes, the relevant handler is returned.
  • In case of trailing slash differences, it may recommend a TSR (if possible).
  • Wildcard handlers are matched depending on the path and updated in the context.

Notes:

  • If no handler exists for the path, nil is returned along with false for TSR.

type UploadedFile

type UploadedFile struct {
	Field string // Field name in the form where the file was uploaded.
	Name  string // Name of the uploaded file.
	Path  string // Path where the uploaded file is saved.
	Size  int64  // Size of the uploaded file in bytes.
}

UploadedFile represents the information of an uploaded file.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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