core

package module
v1.10.4 Latest Latest
Warning

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

Go to latest
Published: Sep 1, 2024 License: MIT Imports: 18 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.IFlyRouter) {
    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 Global IPv4
	GlobalIpv4Addr = "0.0.0.0"

	// SchemaHTTP HTTP schema
	SchemaHTTP = "http"

	// SchemaHTTPS HTTPS schema
	SchemaHTTPS = "https"

	// NetworkTCP Network TCP
	NetworkTCP = "tcp"

	// NetworkTCP4 Network TCP4
	NetworkTCP4 = "tcp4"

	// NetworkTCP6 Network TCP6
	NetworkTCP6 = "tcp6"
)

Network

View Source
const (
	StrGzip    = "gzip"
	StrBr      = "br"
	StrDeflate = "deflate"
	StrBrotli  = "brotli"
)

Compression types

View Source
const (
	CookieSameSiteDisabled   = "disabled"
	CookieSameSiteLaxMode    = "lax"
	CookieSameSiteStrictMode = "strict"
	CookieSameSiteNoneMode   = "none"
)

Cookie SameSite

View Source
const (
	MIMETextXML         = "text/xml"
	MIMETextHTML        = "text/html"
	MIMETextPlain       = "text/plain"
	MIMETextJavaScript  = "text/javascript"
	MIMEApplicationXML  = "application/xml"
	MIMEApplicationJSON = "application/json"
	// Deprecated: use MIMETextJavaScript instead
	MIMEApplicationJavaScript = "application/javascript"
	MIMEApplicationForm       = "application/x-www-form-urlencoded"
	MIMEOctetStream           = "application/octet-stream"
	MIMEMultipartForm         = "multipart/form-data"

	MIMETextXMLCharsetUTF8         = "text/xml; charset=utf-8"
	MIMETextHTMLCharsetUTF8        = "text/html; charset=utf-8"
	MIMETextPlainCharsetUTF8       = "text/plain; charset=utf-8"
	MIMETextJavaScriptCharsetUTF8  = "text/javascript; charset=utf-8"
	MIMEApplicationXMLCharsetUTF8  = "application/xml; charset=utf-8"
	MIMEApplicationJSONCharsetUTF8 = "application/json; charset=utf-8"
	// Deprecated: use MIMETextJavaScriptCharsetUTF8 instead
	MIMEApplicationJavaScriptCharsetUTF8 = "application/javascript; charset=utf-8"
)

MIME types that are commonly used

View Source
const (
	MethodGet     = "GET"     // RFC 7231, 4.3.1
	MethodHead    = "HEAD"    // RFC 7231, 4.3.2
	MethodPost    = "POST"    // RFC 7231, 4.3.3
	MethodPut     = "PUT"     // RFC 7231, 4.3.4
	MethodPatch   = "PATCH"   // RFC 5789
	MethodDelete  = "DELETE"  // RFC 7231, 4.3.5
	MethodConnect = "CONNECT" // RFC 7231, 4.3.6
	MethodOptions = "OPTIONS" // RFC 7231, 4.3.7
	MethodTrace   = "TRACE"   // RFC 7231, 4.3.8
	MethodUse     = "USE"
)

HTTP methods were copied from net/http.

View Source
const (
	StatusContinue           = 100 // RFC 9110, 15.2.1
	StatusSwitchingProtocols = 101 // RFC 9110, 15.2.2
	StatusProcessing         = 102 // RFC 2518, 10.1
	StatusEarlyHints         = 103 // RFC 8297

	StatusOK                          = 200 // RFC 9110, 15.3.1
	StatusCreated                     = 201 // RFC 9110, 15.3.2
	StatusAccepted                    = 202 // RFC 9110, 15.3.3
	StatusNonAuthoritativeInformation = 203 // RFC 9110, 15.3.4
	StatusNoContent                   = 204 // RFC 9110, 15.3.5
	StatusResetContent                = 205 // RFC 9110, 15.3.6
	StatusPartialContent              = 206 // RFC 9110, 15.3.7
	StatusMultiStatus                 = 207 // RFC 4918, 11.1
	StatusAlreadyReported             = 208 // RFC 5842, 7.1
	StatusIMUsed                      = 226 // RFC 3229, 10.4.1

	StatusMultipleChoices   = 300 // RFC 9110, 15.4.1
	StatusMovedPermanently  = 301 // RFC 9110, 15.4.2
	StatusFound             = 302 // RFC 9110, 15.4.3
	StatusSeeOther          = 303 // RFC 9110, 15.4.4
	StatusNotModified       = 304 // RFC 9110, 15.4.5
	StatusUseProxy          = 305 // RFC 9110, 15.4.6
	StatusSwitchProxy       = 306 // RFC 9110, 15.4.7 (Unused)
	StatusTemporaryRedirect = 307 // RFC 9110, 15.4.8
	StatusPermanentRedirect = 308 // RFC 9110, 15.4.9

	StatusBadRequest                   = 400 // RFC 9110, 15.5.1
	StatusUnauthorized                 = 401 // RFC 9110, 15.5.2
	StatusPaymentRequired              = 402 // RFC 9110, 15.5.3
	StatusForbidden                    = 403 // RFC 9110, 15.5.4
	StatusNotFound                     = 404 // RFC 9110, 15.5.5
	StatusMethodNotAllowed             = 405 // RFC 9110, 15.5.6
	StatusNotAcceptable                = 406 // RFC 9110, 15.5.7
	StatusProxyAuthRequired            = 407 // RFC 9110, 15.5.8
	StatusRequestTimeout               = 408 // RFC 9110, 15.5.9
	StatusConflict                     = 409 // RFC 9110, 15.5.10
	StatusGone                         = 410 // RFC 9110, 15.5.11
	StatusLengthRequired               = 411 // RFC 9110, 15.5.12
	StatusPreconditionFailed           = 412 // RFC 9110, 15.5.13
	StatusRequestEntityTooLarge        = 413 // RFC 9110, 15.5.14
	StatusRequestURITooLong            = 414 // RFC 9110, 15.5.15
	StatusUnsupportedMediaType         = 415 // RFC 9110, 15.5.16
	StatusRequestedRangeNotSatisfiable = 416 // RFC 9110, 15.5.17
	StatusExpectationFailed            = 417 // RFC 9110, 15.5.18
	StatusTeapot                       = 418 // RFC 9110, 15.5.19 (Unused)
	StatusMisdirectedRequest           = 421 // RFC 9110, 15.5.20
	StatusUnprocessableEntity          = 422 // RFC 9110, 15.5.21
	StatusLocked                       = 423 // RFC 4918, 11.3
	StatusFailedDependency             = 424 // RFC 4918, 11.4
	StatusTooEarly                     = 425 // RFC 8470, 5.2.
	StatusUpgradeRequired              = 426 // RFC 9110, 15.5.22
	StatusPreconditionRequired         = 428 // RFC 6585, 3
	StatusTooManyRequests              = 429 // RFC 6585, 4
	StatusRequestHeaderFieldsTooLarge  = 431 // RFC 6585, 5
	StatusUnavailableForLegalReasons   = 451 // RFC 7725, 3

	StatusInternalServerError           = 500 // RFC 9110, 15.6.1
	StatusNotImplemented                = 501 // RFC 9110, 15.6.2
	StatusBadGateway                    = 502 // RFC 9110, 15.6.3
	StatusServiceUnavailable            = 503 // RFC 9110, 15.6.4
	StatusGatewayTimeout                = 504 // RFC 9110, 15.6.5
	StatusHTTPVersionNotSupported       = 505 // RFC 9110, 15.6.6
	StatusVariantAlsoNegotiates         = 506 // RFC 2295, 8.1
	StatusInsufficientStorage           = 507 // RFC 4918, 11.5
	StatusLoopDetected                  = 508 // RFC 5842, 7.2
	StatusNotExtended                   = 510 // RFC 2774, 7
	StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
)

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                   = "Authorization"
	HeaderProxyAuthenticate               = "Proxy-Authenticate"
	HeaderProxyAuthorization              = "Proxy-Authorization"
	HeaderWWWAuthenticate                 = "WWW-Authenticate"
	HeaderAge                             = "Age"
	HeaderCacheControl                    = "Cache-Control"
	HeaderClearSiteData                   = "Clear-Site-Data"
	HeaderExpires                         = "Expires"
	HeaderPragma                          = "Pragma"
	HeaderWarning                         = "Warning"
	HeaderAcceptCH                        = "Accept-CH"
	HeaderAcceptCHLifetime                = "Accept-CH-Lifetime"
	HeaderContentDPR                      = "Content-DPR"
	HeaderDPR                             = "DPR"
	HeaderEarlyData                       = "Early-Data"
	HeaderSaveData                        = "Save-Data"
	HeaderViewportWidth                   = "Viewport-Width"
	HeaderWidth                           = "Width"
	HeaderETag                            = "ETag"
	HeaderIfMatch                         = "If-Match"
	HeaderIfModifiedSince                 = "If-Modified-Since"
	HeaderIfNoneMatch                     = "If-None-Match"
	HeaderIfUnmodifiedSince               = "If-Unmodified-Since"
	HeaderLastModified                    = "Last-Modified"
	HeaderVary                            = "Vary"
	HeaderConnection                      = "Connection"
	HeaderKeepAlive                       = "Keep-Alive"
	HeaderAccept                          = "Accept"
	HeaderAcceptCharset                   = "Accept-Charset"
	HeaderAcceptEncoding                  = "Accept-Encoding"
	HeaderAcceptLanguage                  = "Accept-Language"
	HeaderCookie                          = "Cookie"
	HeaderExpect                          = "Expect"
	HeaderMaxForwards                     = "Max-Forwards"
	HeaderSetCookie                       = "Set-Cookie"
	HeaderAccessControlAllowCredentials   = "Access-Control-Allow-Credentials"
	HeaderAccessControlAllowHeaders       = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowMethods       = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowOrigin        = "Access-Control-Allow-Origin"
	HeaderAccessControlExposeHeaders      = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge             = "Access-Control-Max-Age"
	HeaderAccessControlRequestHeaders     = "Access-Control-Request-Headers"
	HeaderAccessControlRequestMethod      = "Access-Control-Request-Method"
	HeaderOrigin                          = "Origin"
	HeaderTimingAllowOrigin               = "Timing-Allow-Origin"
	HeaderXPermittedCrossDomainPolicies   = "X-Permitted-Cross-Domain-Policies"
	HeaderDNT                             = "DNT"
	HeaderTk                              = "Tk"
	HeaderContentDisposition              = "Content-Disposition"
	HeaderContentEncoding                 = "Content-Encoding"
	HeaderContentLanguage                 = "Content-Language"
	HeaderContentLength                   = "Content-Length"
	HeaderContentLocation                 = "Content-Location"
	HeaderContentType                     = "Content-Type"
	HeaderForwarded                       = "Forwarded"
	HeaderVia                             = "Via"
	HeaderXForwardedFor                   = "X-Forwarded-For"
	HeaderXForwardedHost                  = "X-Forwarded-Host"
	HeaderXForwardedProto                 = "X-Forwarded-Proto"
	HeaderXForwardedProtocol              = "X-Forwarded-Protocol"
	HeaderXForwardedSsl                   = "X-Forwarded-Ssl"
	HeaderXUrlScheme                      = "X-Url-Scheme"
	HeaderLocation                        = "Location"
	HeaderFrom                            = "From"
	HeaderHost                            = "Host"
	HeaderReferer                         = "Referer"
	HeaderReferrerPolicy                  = "Referrer-Policy"
	HeaderUserAgent                       = "User-Agent"
	HeaderAllow                           = "Allow"
	HeaderServer                          = "Server"
	HeaderAcceptRanges                    = "Accept-Ranges"
	HeaderContentRange                    = "Content-Range"
	HeaderIfRange                         = "If-Range"
	HeaderRange                           = "Range"
	HeaderContentSecurityPolicy           = "Content-Security-Policy"
	HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
	HeaderCrossOriginResourcePolicy       = "Cross-Origin-Resource-Policy"
	HeaderExpectCT                        = "Expect-CT"
	// Deprecated: use HeaderPermissionsPolicy instead
	HeaderFeaturePolicy           = "Feature-Policy"
	HeaderPermissionsPolicy       = "Permissions-Policy"
	HeaderPublicKeyPins           = "Public-Key-Pins"
	HeaderPublicKeyPinsReportOnly = "Public-Key-Pins-Report-Only"
	HeaderStrictTransportSecurity = "Strict-Transport-Security"
	HeaderUpgradeInsecureRequests = "Upgrade-Insecure-Requests"
	HeaderXContentTypeOptions     = "X-Content-Type-Options"
	HeaderXDownloadOptions        = "X-Download-Options"
	HeaderXFrameOptions           = "X-Frame-Options"
	HeaderXPoweredBy              = "X-Powered-By"
	HeaderXXSSProtection          = "X-XSS-Protection"
	HeaderLastEventID             = "Last-Event-ID"
	HeaderNEL                     = "NEL"
	HeaderPingFrom                = "Ping-From"
	HeaderPingTo                  = "Ping-To"
	HeaderReportTo                = "Report-To"
	HeaderTE                      = "TE"
	HeaderTrailer                 = "Trailer"
	HeaderTransferEncoding        = "Transfer-Encoding"
	HeaderSecWebSocketAccept      = "Sec-WebSocket-Accept"
	HeaderSecWebSocketExtensions  = "Sec-WebSocket-Extensions"
	HeaderSecWebSocketKey         = "Sec-WebSocket-Key"
	HeaderSecWebSocketProtocol    = "Sec-WebSocket-Protocol"
	HeaderSecWebSocketVersion     = "Sec-WebSocket-Version"
	HeaderAcceptPatch             = "Accept-Patch"
	HeaderAcceptPushPolicy        = "Accept-Push-Policy"
	HeaderAcceptSignature         = "Accept-Signature"
	HeaderAltSvc                  = "Alt-Svc"
	HeaderDate                    = "Date"
	HeaderIndex                   = "Index"
	HeaderLargeAllocation         = "Large-Allocation"
	HeaderLink                    = "Link"
	HeaderPushPolicy              = "Push-Policy"
	HeaderRetryAfter              = "Retry-After"
	HeaderServerTiming            = "Server-Timing"
	HeaderSignature               = "Signature"
	HeaderSignedHeaders           = "Signed-Headers"
	HeaderSourceMap               = "SourceMap"
	HeaderUpgrade                 = "Upgrade"
	HeaderXDNSPrefetchControl     = "X-DNS-Prefetch-Control"
	HeaderXPingBack               = "X-Pingback"
	HeaderXRequestID              = "X-Request-ID"
	HeaderXRequestedWith          = "X-Requested-With"
	HeaderXRobotsTag              = "X-Robots-Tag"
	HeaderXUACompatible           = "X-UA-Compatible"
)

HTTP Headers were copied from net/http.

View Source
const MethodWild = "*"

MethodWild wild HTTP method

View Source
const (
	// Version of current gFly
	Version = "v1.8.0"
)

Variables

View Source
var (
	AppName  = utils.Getenv("APP_NAME", "gFly")
	AppCode  = utils.Getenv("APP_CODE", "gfly")
	AppURL   = utils.Getenv("APP_URL", "http://localhost:7789")
	AppEnv   = utils.Getenv("APP_ENV", "local")
	AppDebug = utils.Getenv("APP_DEBUG", true)

	StorageDir = utils.Getenv("STORAGE_DIR", "storage")  // Directory `{APP}/storage`
	TempDir    = utils.Getenv("TEMP_DIR", "storage/tmp") // Directory `{APP}/storage/temp`
	LogDir     = utils.Getenv("LOG_DIR", "storage/logs") // Directory `{APP}/storage/log`
	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",
}

Functions

func RegisterSession added in v1.9.0

func RegisterSession(s ISession)

RegisterSession Get data from session.

func RegisterView added in v1.8.0

func RegisterView(v IView)

RegisterView inject View

Types

type Api

type Api struct {
	Endpoint
}

Api Abstract api

type Config

type Config struct {
	// App name
	//
	// Default app name is used if left blank.
	AppName string

	// Server name for sending in response headers.
	//
	// Default server name is used if left blank.
	Name string

	// 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.
	Concurrency int

	// ReadTimeout is the amount of time allowed to read
	// the full request including body. The connection's read
	// deadline is reset when the connection opens, or for
	// keep-alive connections after the first byte has been read.
	//
	// By default request read timeout is unlimited.
	ReadTimeout time.Duration

	// WriteTimeout is the maximum duration before timing out
	// writes of the response. It is reset after the request handler
	// has returned.
	//
	// By default response write timeout is unlimited.
	WriteTimeout time.Duration

	// IdleTimeout is the maximum amount of time to wait for the
	// next request when keep-alive is enabled. If IdleTimeout
	// is zero, the value of ReadTimeout is used.
	IdleTimeout time.Duration

	// Per-connection buffer size for requests' reading.
	// This also limits the maximum header size.
	//
	// Increase this buffer if your clients send multi-KB RequestURIs
	// and/or multi-KB headers (for example, BIG cookies).
	//
	// Default buffer size is used if not set.
	ReadBufferSize int

	// Per-connection buffer size for responses' writing.
	//
	// Default buffer size is used if not set.
	WriteBufferSize int

	// NoDefaultDate, when set to true, causes the default Date
	// header to be excluded from the Response.
	//
	// The default Date header value is the current date value. When
	// set to true, the Date will not be present.
	NoDefaultDate bool

	// NoDefaultContentType, when set to true, causes the default Content-Type
	// header to be excluded from the Response.
	//
	// The default Content-Type header value is the internal default value. When
	// set to true, the Content-Type will not be present.
	NoDefaultContentType bool

	// Header names are passed as-is without normalization
	// if this option is set.
	//
	// Disabled header names' normalization may be useful only for proxying
	// incoming requests to other servers expecting case-sensitive
	// header names. See https://github.com/valyala/fasthttp/issues/57
	// for details.
	//
	// By default request and response header names are normalized, i.e.
	// The first letter and the first letters following dashes
	// are uppercased, while all the other letters are lowercased.
	// Examples:
	//
	//     * HOST -> Host
	//     * content-type -> Content-Type
	//     * cONTENT-lenGTH -> Content-Length
	DisableHeaderNamesNormalizing bool

	// Whether to disable keep-alive connections.
	//
	// The server will close all the incoming connections after sending
	// the first response to client if this option is set to true.
	//
	// By default keep-alive connections are enabled.
	DisableKeepalive bool

	// Maximum request body size.
	// a zero value means that default values will be honored
	MaxRequestBodySize int

	// NoDefaultServerHeader, when set to true, causes the default Server header
	// to be excluded from the Response.
	//
	// The default Server header value is the value of the Name field or an
	// internal default value in its absence. With this option set to true,
	// the only time a Server header will be sent is if a non-zero length
	// value is explicitly provided during a request.
	NoDefaultServerHeader bool

	// Rejects all non-GET requests if set to true.
	//
	// This option is useful as anti-DoS protection for servers
	// accepting only GET requests and HEAD requests. The request size is limited
	// by ReadBufferSize if GetOnly is set.
	//
	// Server accepts all the requests by default.
	GetOnly bool

	// Aggressively reduces memory usage at the cost of higher CPU usage
	// if set to true.
	//
	// Try enabling this option only if the server consumes too much memory
	// serving mostly idle keep-alive connections. This may reduce memory
	// usage by more than 50%.
	//
	// Aggressive memory usage reduction is disabled by default.
	ReduceMemoryUsage bool

	// StreamRequestBody enables request body streaming,
	// and calls the handler sooner when given body is
	// larger than the current limit.
	StreamRequestBody bool

	// Will not pre parse Multipart Form data if set to true.
	//
	// This option is useful for servers that desire to treat
	// multipart form data as a binary blob, or choose when to parse the data.
	//
	// Server pre parses multipart form data by default.
	DisablePreParseMultipartForm bool

	// When set to true, it will not print out the «gFly» ASCII art and listening address.
	//
	// Default: false
	DisableStartupMessage bool

	// Known networks are "tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only)
	// WARNING: When prefork is set to true, only "tcp4" and "tcp6" can be chose.
	//
	// Default: NetworkTCP4
	Network string

	// When set to true, this will spawn multiple Go processes listening on the same port.
	//
	// Default: false
	Prefork bool

	// CompressedFileSuffix adds suffix to the original file name and
	// tries saving the resulting compressed file under the new file name.
	//
	// Default: ".gz"
	CompressedFileSuffix string
}

type Ctx

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

Ctx HTTP request context

func (*Ctx) Compress

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

Compress Response compressed content with Gzip|Brotli|Deflate (TODO Need more checking)

func (*Ctx) ContentType

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

ContentType sets the response's HTTP content type.

func (*Ctx) Download

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

Download transfers the file from path as an attachment. Typically, browsers will prompt the user for download. By default, the Content-Disposition header filename= parameter is the filepath (this typically appears in the browser dialog). Override this default with the filename parameter.

func (*Ctx) Error

func (c *Ctx) Error(data interface{}) error

Error Response error JSON data.

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 by passing a 'true' argument Sets the Content-Type response HTTP header field based on the filename extension.

func (*Ctx) FormBool

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

FormBool Get bool from POST|PUT request.

func (*Ctx) FormFloat

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

FormFloat Get float from POST|PUT request.

func (*Ctx) FormInt

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

FormInt Get int from POST|PUT request.

func (*Ctx) FormUpload

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

FormUpload Process and get uploaded files from POST|PUT request.

func (*Ctx) FormVal

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

FormVal Get data from POST|PUT request.

func (*Ctx) GetCookie

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

GetCookie get cookie from the request's HTTP header.

func (*Ctx) GetData

func (c *Ctx) GetData(key string) interface{}

GetData Get data from request context Ctx.

func (*Ctx) GetReqHeaders

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

GetReqHeaders returns the HTTP request headers. Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting instead.

func (*Ctx) GetSession added in v1.9.0

func (c *Ctx) GetSession(key string) interface{}

GetSession Get data from session.

func (*Ctx) HTML

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

HTML sets the HTTP response body for HTML types. This means no type assertion, recommended for faster performance

func (*Ctx) JSON

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

JSON Response json content.

func (*Ctx) NoContent

func (c *Ctx) NoContent() error

NoContent Response no content.

func (*Ctx) OriginalURL

func (c *Ctx) OriginalURL() string

OriginalURL contains the original request URL. Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting to use the value outside the Handler.

func (*Ctx) ParseBody

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

ParseBody Parse body JSON data to struct data type.

func (*Ctx) ParseQuery

func (c *Ctx) ParseQuery(out interface{}) error

ParseQuery Parse query string to struct data type.

func (*Ctx) Path

func (c *Ctx) Path() string

Path returns path URI

func (*Ctx) PathVal

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

PathVal Get data from Path request.

func (*Ctx) Queries

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

Queries Get data from Query string.

func (*Ctx) QueryBool

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

QueryBool Get bool from Query string.

func (*Ctx) QueryFloat

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

QueryFloat Get float from Query string.

func (*Ctx) QueryInt

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

QueryInt Get int from Query string.

func (*Ctx) QueryStr

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

QueryStr Get data from Query string.

func (*Ctx) Raw

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

Raw sets the HTTP response body without copying it. From this point onward, the body argument must not be changed.

func (*Ctx) Redirect

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

Redirect Send redirect.

func (*Ctx) Root

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

Root Get original HTTP request context.

func (*Ctx) Router

func (c *Ctx) Router() *Router

Router Get original Router.

func (*Ctx) SetCookie

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

SetCookie set cookie to the response's HTTP header.

func (*Ctx) SetData

func (c *Ctx) SetData(key string, data interface{})

SetData Keep data in request context Ctx.

func (*Ctx) SetHeader

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

SetHeader sets the response's HTTP header field to the specified key, value.

func (*Ctx) SetSession added in v1.9.0

func (c *Ctx) SetSession(key string, data interface{})

SetSession Keep data in session.

func (*Ctx) Status

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

Status sets the response's HTTP code.

func (*Ctx) Stream

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

Stream sets response body stream and optional body size.

func (*Ctx) String

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

String sets the HTTP response body for string types. This means no type assertion, recommended for faster performance

func (*Ctx) Success

func (c *Ctx) Success(data interface{}) error

Success Response success JSON data.

func (*Ctx) View

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

View Render from template file.

type Data

type Data Map

Data generic map type for almost usage purpose

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) interface{}

func (*DefaultSession) Set added in v1.9.0

func (v *DefaultSession) Set(c *Ctx, key string, value interface{})

type DefaultView added in v1.8.0

type DefaultView struct {
}

func (*DefaultView) Parse added in v1.8.0

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

func (*DefaultView) Writer added in v1.8.0

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

type Endpoint

type Endpoint struct{}

Endpoint Default handler

func (*Endpoint) Handle

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

func (*Endpoint) Validate

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

type FnHookMiddleware

type FnHookMiddleware func(fly IFlyMiddleware)

type FnHookRoute

type FnHookRoute func(fly IFlyRouter)

type GFly

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

GFly Struct define main elements in app.

func (*GFly) CONNECT

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

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

func (*GFly) DELETE

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

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

func (*GFly) GET

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

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

func (*GFly) Group

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

Group Create a group Handler functions.

func (*GFly) HEAD

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

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

func (*GFly) Middleware

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

Middleware is a shortcut for Middleware.Group(middlewares ...MiddlewareHandler) Example

group.POST("/one", gfly.IFly.Middleware(middleware.RuleMiddlewareFunc)(api.NewDefaultApi()))

func (*GFly) OPTIONS

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

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

func (*GFly) PATCH

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

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

func (*GFly) POST

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

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

func (*GFly) PUT

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

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

func (*GFly) RegisterMiddleware

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

RegisterMiddleware Register Middleware

func (*GFly) RegisterRouter

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

RegisterRouter Register Router

func (*GFly) Router

func (fly *GFly) Router() *Router

Router Get root router in gFly app.

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)

func (*GFly) Use

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

Use Middleware for global (All requests) Example

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

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)

func (*Group) DELETE

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

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

func (*Group) GET

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

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

func (*Group) Group

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

Group Create a group Handler functions.

func (*Group) HEAD

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

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

func (*Group) OPTIONS

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

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

func (*Group) PATCH

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

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

func (*Group) POST

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

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

func (*Group) PUT

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

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

func (*Group) TRACE

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

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

func (*Group) Use

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

Use apply middleware for all router group.

type IData

type IData interface {
	// SetData Keep data in request context Ctx.
	SetData(key string, data interface{})
	// GetData Get data from request context Ctx.
	GetData(key string) interface{}
	// SetSession Keep data in request context Ctx.
	SetSession(key string, data interface{})
	// GetSession Get data from request context Ctx.
	GetSession(key string) interface{}
}

type IFly

type IFly interface {
	IFlyRouter
	IFlyMiddleware
	// Run start application
	Run()
	// Router web router
	Router() *Router
	// RegisterMiddleware register middlewares
	RegisterMiddleware(fn ...FnHookMiddleware)
	// RegisterRouter register router
	RegisterRouter(fn ...FnHookRoute)
}

IFly Interface to declare all methods for gFly struct.

func New

func New(config ...Config) IFly

New Create new gFly app.

type IFlyMiddleware

type IFlyMiddleware interface {
	// Use middleware to global (All requests)
	Use(middlewares ...MiddlewareHandler)
	// Middleware is a shortcut for Middleware.Group(middlewares ...MiddlewareHandler)
	Middleware(middleware ...MiddlewareHandler) func(IHandler) IHandler
}

IFlyMiddleware Interface to declare all Middleware methods for gFly struct.

type IFlyRouter

type IFlyRouter interface {
	// GET Http GET method
	GET(path string, handler IHandler)
	// HEAD Http HEAD method
	HEAD(path string, handler IHandler)
	// POST Http POST method
	POST(path string, handler IHandler)
	// PUT Http PUT method
	PUT(path string, handler IHandler)
	// PATCH Http PATCH method
	PATCH(path string, handler IHandler)
	// DELETE Http DELETE method
	DELETE(path string, handler IHandler)
	// CONNECT Http CONNECT method
	CONNECT(path string, handler IHandler)
	// OPTIONS Http OPTIONS method
	OPTIONS(path string, handler IHandler)
	// TRACE Http TRACE method
	TRACE(path string, handler IHandler)
	// Group multi routers
	Group(path string, groupFunc func(*Group))
}

IFlyRouter Interface to declare all HTTP methods for gFly struct.

type IGroupMiddleware

type IGroupMiddleware interface {
	// Use apply middleware for all router group.
	// Important: Should put the code at the top of group router.
	Use(middlewares ...MiddlewareHandler)
}

IGroupMiddleware Interface to declare all Middleware methods for gFly struct.

type IGroupRouter

type IGroupRouter interface {
	// GET Http GET method
	GET(path string, handler IHandler)
	// HEAD Http HEAD method
	HEAD(path string, handler IHandler)
	// POST Http POST method
	POST(path string, handler IHandler)
	// PUT Http PUT method
	PUT(path string, handler IHandler)
	// PATCH Http PATCH method
	PATCH(path string, handler IHandler)
	// DELETE Http DELETE method
	DELETE(path string, handler IHandler)
	// CONNECT Http CONNECT method
	CONNECT(path string, handler IHandler)
	// OPTIONS Http OPTIONS method
	OPTIONS(path string, handler IHandler)
	// TRACE Http TRACE method
	TRACE(path string, handler IHandler)
	// Group multi routers
	Group(path string, groupFunc func(*Group))
}

IGroupRouter Interface to declare all HTTP methods.

type IHandler

type IHandler interface {
	Validate(c *Ctx) error
	Handle(c *Ctx) error
}

IHandler Interface a handler request.

type IHeader

type IHeader interface {
	// Status sets the response's HTTP code.
	Status(code int) *Ctx
	// ContentType sets the response's HTTP content type.
	ContentType(mime string) *Ctx
	// SetHeader sets the response's HTTP header field to the specified key, value.
	SetHeader(key, val string) *Ctx
	// SetCookie set cookie to the response's HTTP header.
	SetCookie(key, value string) *Ctx
	// GetCookie get cookie from the request's HTTP header.
	GetCookie(key string) string
	// GetReqHeaders returns the HTTP request headers.
	GetReqHeaders() map[string][]string
	// Path returns path URI
	Path() string
}

type IMiddleware

type IMiddleware interface {
	Group(middlewares ...MiddlewareHandler) func(IHandler) IHandler
}

IMiddleware Middleware interface

func NewMiddleware

func NewMiddleware() IMiddleware

type IRequestData

type IRequestData interface {
	// ParseBody Parse body to struct data type.
	ParseBody(data any) error
	// ParseQuery Parse query string to struct data type.
	ParseQuery(data any) error
	// FormVal Get data from POST|PUT request.
	FormVal(key string) []byte
	// FormInt Get int from POST|PUT request.
	FormInt(key string) (int, error)
	// FormBool Get bool from POST|PUT request.
	FormBool(key string) (bool, error)
	// FormFloat Get float from POST|PUT request.
	FormFloat(key string) (float64, error)
	// FormUpload Process and get uploaded files from POST|PUT request.
	FormUpload(files ...string) ([]UploadedFile, error)
	// Queries Get data from Query string.
	Queries() map[string]string
	// QueryStr Get data from Query string.
	QueryStr(key string) string
	// QueryInt Get int from Query string.
	QueryInt(key string) (int, error)
	// QueryBool Get bool from Query string.
	QueryBool(key string) (bool, error)
	// QueryFloat Get float from Query string.
	QueryFloat(key string) (float64, error)
	// PathVal Get data from Path request.
	PathVal(key string) string
	// OriginalURL Original URL.
	OriginalURL() string
}

type IResponse

type IResponse interface {
	// Success Response success JSON data.
	Success(data interface{}) error
	// Error Response error JSON data.
	Error(data interface{}) error
	// NoContent Response no content.
	NoContent() error
	// View Load template page.
	View(template string, data Data) error
	// JSON sets the HTTP response body for JSON type.
	JSON(data JsonData) error
	// HTML sets the HTTP response body for HTML type.
	HTML(body string) error
	// String sets the HTTP response body for String type.
	String(body string) error
	// Raw sets the HTTP response body without copying it.
	Raw(body []byte) error
	// Stream sets response body stream and optional body size.
	Stream(stream io.Reader, size ...int) error
	// Redirect Send redirect.
	Redirect(path string) error
	// Download transfers the file from path as an attachment.
	Download(file string, filename ...string) error
	// File transfers the file from the given path.
	File(file string, compress ...bool) error
}

type ISession added in v1.9.0

type ISession interface {
	Set(c *Ctx, key string, value interface{})
	Get(c *Ctx, key string) interface{}
}

type IView added in v1.8.0

type IView interface {
	// Parse build string from template `tpl` and data `data`
	Parse(tpl string, data Data) string
	// Writer set writer `w` from template `tpl` and data `data`
	Writer(tpl string, data Data, writer io.Writer) error
}

type JsonData

type JsonData interface{}

JsonData generic JSON data type for almost usage purpose

type Map

type Map map[string]any

Map generic map type for almost usage purpose

type Middleware

type Middleware struct{}

Middleware Middleware type

func (*Middleware) Group

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

Group Create a group Middleware functions. Implement for IMiddleware interface

type MiddlewareHandler

type MiddlewareHandler func(ctx *Ctx) error

MiddlewareHandler must return RequestHandler for continuing or error to stop on it.

type Page

type Page struct {
	Endpoint
}

Page Abstract web page

type RequestHandler

type RequestHandler func(ctx *Ctx) error

RequestHandler A wrapper of fasthttp.RequestHandler

type Router

type Router struct {

	// 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 that were
	// registered when this option was enabled.
	SaveMatchedRoutePath bool

	// Enables automatic redirection if the current route can't be matched but a
	// handler for the path with (without) the trailing slash exists.
	// For example if /foo/ is requested but a route only exists for /foo, the
	// client is redirected to /foo with http status code 301 for GET requests
	// and 308 for all other request methods.
	RedirectTrailingSlash bool

	// If enabled, the router tries to fix the current request path, if no
	// handle is registered for it.
	// First superfluous path elements like ../ or // are removed.
	// Afterwards the router does a case-insensitive lookup of the cleaned path.
	// If a handle can be found for this route, the router makes a redirection
	// to the corrected path with status code 301 for GET requests and 308 for
	// all other request methods.
	// For example /FOO and /..//Foo could be redirected to /foo.
	// RedirectTrailingSlash is independent of this option.
	RedirectFixedPath bool

	// If enabled, the router checks if another method is allowed for the
	// current route, if the current request can not be routed.
	// If this is the case, the request is answered with 'Method Not Allowed'
	// and HTTP status code 405.
	// If no other Method is allowed, the request is delegated to the NotFound
	// handler.
	HandleMethodNotAllowed bool

	// If enabled, the router automatically replies to OPTIONS requests.
	// Custom OPTIONS handlers take priority over automatic replies.
	HandleOPTIONS bool

	// An optional RequestHandler that is called on automatic OPTIONS requests.
	// The handler is only called if HandleOPTIONS is true and no OPTIONS
	// handler for the specific path was set.
	// The "Allowed" header is set before calling the handler.
	GlobalOPTIONS RequestHandler

	// Configurable RequestHandler which is called when no matching route is
	// found. If it is not set, default NotFound is used.
	NotFound RequestHandler

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

	// Function to handle panics recovered from http handlers.
	// It should be used to generate a error page and return the http error code
	// 500 (Internal Server Error).
	// The handler can be used to keep your server from crashing because of
	// unrecovered panics.
	PanicHandler func(*Ctx, interface{})
	// contains filtered or unexported fields
}

Router is a RequestHandler which can be used to dispatch requests to different handler functions via configurable routes

func NewRouter

func NewRouter() *Router

NewRouter returns a new router. Path auto-correction, including trailing slashes, is enabled by default.

func (*Router) CONNECT

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

CONNECT is a shortcut for router.Handle(fasthttp.MethodConnect, path, handler)

func (*Router) DELETE

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

DELETE is a shortcut for router.Handle(fasthttp.MethodDelete, path, handler)

func (*Router) GET

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

GET is a shortcut for router.Handle(fasthttp.MethodGet, path, handler)

func (*Router) Group

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

Group returns a new group. Path auto-correction, including trailing slashes, is enabled by default.

func (*Router) HEAD

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

HEAD is a shortcut for router.Handle(fasthttp.MethodHead, path, handler)

func (*Router) Handle

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

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

For GET, POST, PUT, PATCH and DELETE requests the respective shortcut functions can be used.

This function is intended for bulk loading and to allow the usage of less frequently used, non-standardized or custom methods (e.g. for internal communication with a proxy).

func (*Router) Handler

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

Handler makes the router implement the http.Handler interface.

func (*Router) List

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

List returns all registered routes grouped by method

func (*Router) Lookup

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

Lookup allows the manual lookup of a method + path combo. This is e.g. useful to build a framework around this router. If the path was found, it returns the handler function. Otherwise the second return value indicates whether a redirection to the same path with an extra / without the trailing slash should be performed.

func (*Router) Mutable

func (r *Router) Mutable(v bool)

Mutable allows updating the route handler

It's disabled by default

WARNING: Use with care. It could generate unexpected behaviours

func (*Router) OPTIONS

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

OPTIONS is a shortcut for router.Handle(fasthttp.MethodOptions, path, handler)

func (*Router) PATCH

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

PATCH is a shortcut for router.Handle(fasthttp.MethodPatch, path, handler)

func (*Router) POST

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

POST is a shortcut for router.Handle(fasthttp.MethodPost, path, handler)

func (*Router) PUT

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

PUT is a shortcut for router.Handle(fasthttp.MethodPut, path, handler)

func (*Router) ServeFiles

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

ServeFiles serves files from the given file system root. The path must end with "/{filepath:*}", files are then served from the local path /defined/root/dir/{filepath:*}. For example if root is "/etc" and {filepath:*} is "passwd", the local file "/etc/passwd" would be served. Internally a fasthttp.FSHandler is used, therefore fasthttp.NotFound is used instead Use:

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

func (*Router) ServeFilesCustom

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

ServeFilesCustom serves files from the given file system settings. The path must end with "/{filepath:*}", files are then served from the local path /defined/root/dir/{filepath:*}. For example if root is "/etc" and {filepath:*} is "passwd", the local file "/etc/passwd" would be served. Internally a fasthttp.FSHandler is used, therefore http.NotFound is used instead of the Router's NotFound handler. Use:

router.ServeFilesCustom("/src/{filepath:*}", *customFS)

func (*Router) TRACE

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

TRACE is a shortcut for router.Handle(fasthttp.MethodTrace, path, handler)

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

func NewTree

func NewTree() *Tree

NewTree returns an empty routes storage

func (*Tree) Add

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

Add adds a node with the given handle to the path.

WARNING: Not concurrency-safe!

func (*Tree) FindCaseInsensitivePath

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

FindCaseInsensitivePath makes a case-insensitive lookup of the given path and tries to find a handler. It can optionally also fix trailing slashes. It returns the case-corrected path and a bool indicating whether the lookup was successful.

func (*Tree) Get

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

Get returns the handle registered with the given path (key). The values of param/wildcard are saved as ctx.UserValue. If no handle can be found, a TSR (trailing slash redirect) recommendation is made if a handle exists with an extra (without the) trailing slash for the given path.

type UploadedFile

type UploadedFile struct {
	Field string // Field File name in form
	Name  string // Name Uploaded file name
	Path  string // Path Uploaded file path
	Size  int64  // Size Uploaded file size
}

UploadedFile uploaded file info.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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