Documentation
¶
Index ¶
- Constants
- Variables
- func RegisterSession(s ISession)
- func RegisterView(v IView)
- type Api
- type Config
- type Ctx
- func (c *Ctx) Compress(body []byte) error
- func (c *Ctx) ContentType(mime string) *Ctx
- func (c *Ctx) Download(file string, filename ...string) error
- func (c *Ctx) Error(data interface{}) error
- func (c *Ctx) File(file string, compress ...bool) error
- func (c *Ctx) FormBool(key string) (bool, error)
- func (c *Ctx) FormFloat(key string) (float64, error)
- func (c *Ctx) FormInt(key string) (int, error)
- func (c *Ctx) FormUpload(files ...string) ([]UploadedFile, error)
- func (c *Ctx) FormVal(key string) []byte
- func (c *Ctx) GetCookie(key string) string
- func (c *Ctx) GetData(key string) interface{}
- func (c *Ctx) GetReqHeaders() map[string][]string
- func (c *Ctx) GetSession(key string) interface{}
- func (c *Ctx) HTML(body string) error
- func (c *Ctx) JSON(data JsonData) error
- func (c *Ctx) NoContent() error
- func (c *Ctx) OriginalURL() string
- func (c *Ctx) ParseBody(data any) error
- func (c *Ctx) ParseQuery(out interface{}) error
- func (c *Ctx) Path() string
- func (c *Ctx) PathVal(key string) string
- func (c *Ctx) Queries() map[string]string
- func (c *Ctx) QueryBool(key string) (bool, error)
- func (c *Ctx) QueryFloat(key string) (float64, error)
- func (c *Ctx) QueryInt(key string) (int, error)
- func (c *Ctx) QueryStr(key string) string
- func (c *Ctx) Raw(body []byte) error
- func (c *Ctx) Redirect(path string) error
- func (c *Ctx) Root() *fasthttp.RequestCtx
- func (c *Ctx) Router() *Router
- func (c *Ctx) SetCookie(key, value string) *Ctx
- func (c *Ctx) SetData(key string, data interface{})
- func (c *Ctx) SetHeader(key, val string) *Ctx
- func (c *Ctx) SetSession(key string, data interface{})
- func (c *Ctx) Status(code int) *Ctx
- func (c *Ctx) Stream(stream io.Reader, size ...int) error
- func (c *Ctx) String(body string) error
- func (c *Ctx) Success(data interface{}) error
- func (c *Ctx) View(template string, data Data) error
- type Data
- type DefaultSession
- type DefaultView
- type Endpoint
- type FnHookMiddleware
- type FnHookRoute
- type GFly
- func (fly *GFly) CONNECT(path string, handler IHandler)
- func (fly *GFly) DELETE(path string, handler IHandler)
- func (fly *GFly) GET(path string, handler IHandler)
- func (fly *GFly) Group(path string, groupFunc func(*Group))
- func (fly *GFly) HEAD(path string, handler IHandler)
- func (fly *GFly) Middleware(middlewares ...MiddlewareHandler) func(IHandler) IHandler
- func (fly *GFly) OPTIONS(path string, handler IHandler)
- func (fly *GFly) PATCH(path string, handler IHandler)
- func (fly *GFly) POST(path string, handler IHandler)
- func (fly *GFly) PUT(path string, handler IHandler)
- func (fly *GFly) RegisterMiddleware(fn ...FnHookMiddleware)
- func (fly *GFly) RegisterRouter(fn ...FnHookRoute)
- func (fly *GFly) Router() *Router
- func (fly *GFly) Run()
- func (fly *GFly) TRACE(path string, handler IHandler)
- func (fly *GFly) Use(middlewares ...MiddlewareHandler)
- type Group
- func (g *Group) CONNECT(path string, handler IHandler)
- func (g *Group) DELETE(path string, handler IHandler)
- func (g *Group) GET(path string, handler IHandler)
- func (g *Group) Group(path string, groupFunc func(*Group))
- func (g *Group) HEAD(path string, handler IHandler)
- func (g *Group) OPTIONS(path string, handler IHandler)
- func (g *Group) PATCH(path string, handler IHandler)
- func (g *Group) POST(path string, handler IHandler)
- func (g *Group) PUT(path string, handler IHandler)
- func (g *Group) TRACE(path string, handler IHandler)
- func (g *Group) Use(middlewares ...MiddlewareHandler)
- type IData
- type IFly
- type IFlyMiddleware
- type IFlyRouter
- type IGroupMiddleware
- type IGroupRouter
- type IHandler
- type IHeader
- type IMiddleware
- type IRequestData
- type IResponse
- type ISession
- type IView
- type JsonData
- type Map
- type Middleware
- type MiddlewareHandler
- type Page
- type RequestHandler
- type Router
- func (r *Router) CONNECT(path string, handler IHandler)
- func (r *Router) DELETE(path string, handler IHandler)
- func (r *Router) GET(path string, handler IHandler)
- func (r *Router) Group(path string) *Group
- func (r *Router) HEAD(path string, handler IHandler)
- func (r *Router) Handle(method, path string, handler IHandler)
- func (r *Router) Handler(ctx *Ctx) error
- func (r *Router) List() map[string][]string
- func (r *Router) Lookup(method, path string, ctx *Ctx) (IHandler, bool)
- func (r *Router) Mutable(v bool)
- func (r *Router) OPTIONS(path string, handler IHandler)
- func (r *Router) PATCH(path string, handler IHandler)
- func (r *Router) POST(path string, handler IHandler)
- func (r *Router) PUT(path string, handler IHandler)
- func (r *Router) ServeFiles(path, rootPath string)
- func (r *Router) ServeFilesCustom(path string, fs *fasthttp.FS)
- func (r *Router) TRACE(path string, handler IHandler)
- type Tree
- type UploadedFile
Constants ¶
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
const ( StrGzip = "gzip" StrBr = "br" StrDeflate = "deflate" StrBrotli = "brotli" )
Compression types
const ( CookieSameSiteDisabled = "disabled" CookieSameSiteLaxMode = "lax" CookieSameSiteStrictMode = "strict" CookieSameSiteNoneMode = "none" )
Cookie SameSite
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
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.
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 StatusPaymentRequired = 402 // RFC 9110, 15.5.3 StatusForbidden = 403 // RFC 9110, 15.5.4 StatusNotFound = 404 // RFC 9110, 15.5.5 StatusMethodNotAllowed = 405 // RFC 9110, 15.5.6 StatusNotAcceptable = 406 // RFC 9110, 15.5.7 StatusProxyAuthRequired = 407 // RFC 9110, 15.5.8 StatusRequestTimeout = 408 // RFC 9110, 15.5.9 StatusConflict = 409 // RFC 9110, 15.5.10 StatusGone = 410 // RFC 9110, 15.5.11 StatusLengthRequired = 411 // RFC 9110, 15.5.12 StatusPreconditionFailed = 412 // RFC 9110, 15.5.13 StatusRequestEntityTooLarge = 413 // RFC 9110, 15.5.14 StatusRequestURITooLong = 414 // RFC 9110, 15.5.15 StatusUnsupportedMediaType = 415 // RFC 9110, 15.5.16 StatusRequestedRangeNotSatisfiable = 416 // RFC 9110, 15.5.17 StatusExpectationFailed = 417 // RFC 9110, 15.5.18 StatusTeapot = 418 // RFC 9110, 15.5.19 (Unused) StatusMisdirectedRequest = 421 // RFC 9110, 15.5.20 StatusUnprocessableEntity = 422 // RFC 9110, 15.5.21 StatusLocked = 423 // RFC 4918, 11.3 StatusFailedDependency = 424 // RFC 4918, 11.4 StatusTooEarly = 425 // RFC 8470, 5.2. StatusUpgradeRequired = 426 // RFC 9110, 15.5.22 StatusPreconditionRequired = 428 // RFC 6585, 3 StatusTooManyRequests = 429 // RFC 6585, 4 StatusRequestHeaderFieldsTooLarge = 431 // RFC 6585, 5 StatusInternalServerError = 500 // RFC 9110, 15.6.1 StatusNotImplemented = 501 // RFC 9110, 15.6.2 StatusBadGateway = 502 // RFC 9110, 15.6.3 StatusGatewayTimeout = 504 // RFC 9110, 15.6.5 StatusHTTPVersionNotSupported = 505 // RFC 9110, 15.6.6 StatusVariantAlsoNegotiates = 506 // RFC 2295, 8.1 StatusInsufficientStorage = 507 // RFC 4918, 11.5 StatusLoopDetected = 508 // RFC 5842, 7.2 StatusNotExtended = 510 // RFC 2774, 7 StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6 )
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
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.
const MethodWild = "*"
MethodWild wild HTTP method
const (
// Version of current gFly
Version = "v1.8.0"
)
Variables ¶
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/temp") // 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` )
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.
Types ¶
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 ¶
Compress Response compressed content with Gzip|Brotli|Deflate (TODO Need more checking)
func (*Ctx) ContentType ¶
ContentType sets the response's HTTP content type.
func (*Ctx) Download ¶
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) File ¶
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) FormUpload ¶
func (c *Ctx) FormUpload(files ...string) ([]UploadedFile, error)
FormUpload Process and get uploaded files from POST|PUT request.
func (*Ctx) GetReqHeaders ¶
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
GetSession Get data from session.
func (*Ctx) HTML ¶
HTML sets the HTTP response body for HTML types. This means no type assertion, recommended for faster performance
func (*Ctx) OriginalURL ¶
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) ParseQuery ¶
ParseQuery Parse query string to struct data type.
func (*Ctx) QueryFloat ¶
QueryFloat Get float from Query string.
func (*Ctx) Raw ¶
Raw sets the HTTP response body without copying it. From this point onward, the body argument must not be changed.
func (*Ctx) Root ¶
func (c *Ctx) Root() *fasthttp.RequestCtx
Root Get original HTTP request context.
func (*Ctx) SetHeader ¶
SetHeader sets the response's HTTP header field to the specified key, value.
func (*Ctx) SetSession ¶ added in v1.9.0
SetSession Keep data in session.
func (*Ctx) String ¶
String sets the HTTP response body for string types. This means no type assertion, recommended for faster performance
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 {
}
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) 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) RegisterMiddleware ¶
func (fly *GFly) RegisterMiddleware(fn ...FnHookMiddleware)
RegisterMiddleware Register Middleware
func (*GFly) RegisterRouter ¶
func (fly *GFly) RegisterRouter(fn ...FnHookRoute)
RegisterRouter Register Router
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) 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.
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 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 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 ¶
MiddlewareHandler must return RequestHandler for continuing or error to stop on it.
type RequestHandler ¶
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 ¶
CONNECT is a shortcut for router.Handle(fasthttp.MethodConnect, path, handler)
func (*Router) DELETE ¶
DELETE is a shortcut for router.Handle(fasthttp.MethodDelete, path, handler)
func (*Router) Group ¶
Group returns a new group. Path auto-correction, including trailing slashes, is enabled by default.
func (*Router) Handle ¶
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) Lookup ¶
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 ¶
Mutable allows updating the route handler
It's disabled by default ¶
WARNING: Use with care. It could generate unexpected behaviours
func (*Router) OPTIONS ¶
OPTIONS is a shortcut for router.Handle(fasthttp.MethodOptions, path, handler)
func (*Router) ServeFiles ¶
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 ¶
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)
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 (*Tree) Add ¶
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 ¶
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.