evo

package module
v2.0.0-...-10e4721 Latest Latest
Warning

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

Go to latest
Published: Mar 28, 2024 License: MIT, MIT Imports: 33 Imported by: 0

README

EVO Framework

EVO Framework is a backend development solution designed to facilitate efficient development using the Go programming language. It is built with a focus on modularity and follows the MVC (Model-View-Controller) architectural pattern. The core of EVO Framework is highly extensible, allowing for seamless extension or replacement of its main modules.

Key Features

  • Modularity: EVO Framework promotes modularity, enabling developers to structure their codebase in a modular manner.
  • MVC Structure: Following the widely adopted MVC pattern, EVO Framework separates concerns and improves code organization.
  • Comprehensive Toolset: EVO Framework provides a rich set of tools, eliminating the need for developers to deal with low-level libraries and technologies.
  • Enhanced Readability: By leveraging the EVO Framework, your code becomes more readable and clear, enhancing collaboration and maintainability.

With EVO Framework, you can focus on your programming logic and rapidly develop robust backend solutions without getting bogged down by intricate implementation details.

Table of Contents

Getting Started

To get started with EVO Framework, follow these steps:

  1. Install EVO Framework by running the following command:
    $ go get github.com/getevo/evo/v2
    
  2. Create Minimum Configuration File
#config.yml
Database:
   Cache: "false"
   ConnMaxLifTime: 1h
   Database: "database"
   Debug: "3"
   Enabled: "false"
   MaxIdleConns: "10"
   MaxOpenConns: "100"
   Params: ""
   Password: "password"
   SSLMode: "false"
   Server: 127.0.0.1:3306
   SlowQueryThreshold: 500ms
   Type: mysql
   Username: root
HTTP:
   BodyLimit: 1kb
   CaseSensitive: "false"
   CompressedFileSuffix: .evo.gz
   Concurrency: "1024"
   DisableDefaultContentType: "false"
   DisableDefaultDate: "false"
   DisableHeaderNormalizing: "false"
   DisableKeepalive: "false"
   ETag: "false"
   GETOnly: "false"
   Host: 0.0.0.0
   IdleTimeout: "0"
   Immutable: "false"
   Network: ""
   Port: "8080"
   Prefork: "false"
   ProxyHeader: X-Forwarded-For
   ReadBufferSize: 8kb
   ReadTimeout: 1s
   ReduceMemoryUsage: "false"
   ServerHeader: EVO
   StrictRouting: "false"
   UnescapePath: "false"
   EnablePrintRoutes: false
   WriteBufferSize: 4kb
   WriteTimeout: 5s

  1. Initialize the EVO Framework and start building your application:
package main

import (
   "github.com/getevo/evo/v2"
)

func main() {
    // initialize evo
    evo.Setup()
	
    //your code goes here ...
    evo.Run()
}

Documentation

Index

Constants

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

)

HTTP methods were copied from net/http.

View Source
const (
	MIMETextXML               = "text/xml"
	MIMETextHTML              = "text/html"
	MIMETextPlain             = "text/plain"
	MIMEApplicationXML        = "application/xml"
	MIMEApplicationJSON       = "application/json"
	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"
	MIMEApplicationXMLCharsetUTF8        = "application/xml; charset=utf-8"
	MIMEApplicationJSONCharsetUTF8       = "application/json; charset=utf-8"
	MIMEApplicationJavaScriptCharsetUTF8 = "application/javascript; charset=utf-8"
)

MIME types that are commonly used

View Source
const (
	StatusContinue                      = 100 // RFC 7231, 6.2.1
	StatusSwitchingProtocols            = 101 // RFC 7231, 6.2.2
	StatusProcessing                    = 102 // RFC 2518, 10.1
	StatusEarlyHints                    = 103 // RFC 8297
	StatusOK                            = 200 // RFC 7231, 6.3.1
	StatusCreated                       = 201 // RFC 7231, 6.3.2
	StatusAccepted                      = 202 // RFC 7231, 6.3.3
	StatusNonAuthoritativeInformation   = 203 // RFC 7231, 6.3.4
	StatusNoContent                     = 204 // RFC 7231, 6.3.5
	StatusResetContent                  = 205 // RFC 7231, 6.3.6
	StatusPartialContent                = 206 // RFC 7233, 4.1
	StatusMultiStatus                   = 207 // RFC 4918, 11.1
	StatusAlreadyReported               = 208 // RFC 5842, 7.1
	StatusIMUsed                        = 226 // RFC 3229, 10.4.1
	StatusMultipleChoices               = 300 // RFC 7231, 6.4.1
	StatusMovedPermanently              = 301 // RFC 7231, 6.4.2
	StatusFound                         = 302 // RFC 7231, 6.4.3
	StatusSeeOther                      = 303 // RFC 7231, 6.4.4
	StatusNotModified                   = 304 // RFC 7232, 4.1
	StatusUseProxy                      = 305 // RFC 7231, 6.4.5
	StatusTemporaryRedirect             = 307 // RFC 7231, 6.4.7
	StatusPermanentRedirect             = 308 // RFC 7538, 3
	StatusBadRequest                    = 400 // RFC 7231, 6.5.1
	StatusUnauthorized                  = 401 // RFC 7235, 3.1
	StatusPaymentRequired               = 402 // RFC 7231, 6.5.2
	StatusForbidden                     = 403 // RFC 7231, 6.5.3
	StatusNotFound                      = 404 // RFC 7231, 6.5.4
	StatusMethodNotAllowed              = 405 // RFC 7231, 6.5.5
	StatusNotAcceptable                 = 406 // RFC 7231, 6.5.6
	StatusProxyAuthRequired             = 407 // RFC 7235, 3.2
	StatusRequestTimeout                = 408 // RFC 7231, 6.5.7
	StatusConflict                      = 409 // RFC 7231, 6.5.8
	StatusGone                          = 410 // RFC 7231, 6.5.9
	StatusLengthRequired                = 411 // RFC 7231, 6.5.10
	StatusPreconditionFailed            = 412 // RFC 7232, 4.2
	StatusRequestEntityTooLarge         = 413 // RFC 7231, 6.5.11
	StatusRequestURITooLong             = 414 // RFC 7231, 6.5.12
	StatusUnsupportedMediaType          = 415 // RFC 7231, 6.5.13
	StatusRequestedRangeNotSatisfiable  = 416 // RFC 7233, 4.4
	StatusExpectationFailed             = 417 // RFC 7231, 6.5.14
	StatusTeapot                        = 418 // RFC 7168, 2.3.3
	StatusMisdirectedRequest            = 421 // RFC 7540, 9.1.2
	StatusUnprocessableEntity           = 422 // RFC 4918, 11.2
	StatusLocked                        = 423 // RFC 4918, 11.3
	StatusFailedDependency              = 424 // RFC 4918, 11.4
	StatusTooEarly                      = 425 // RFC 8470, 5.2.
	StatusUpgradeRequired               = 426 // RFC 7231, 6.5.15
	StatusPreconditionRequired          = 428 // RFC 6585, 3
	StatusTooManyRequests               = 429 // RFC 6585, 4
	StatusRequestHeaderFieldsTooLarge   = 431 // RFC 6585, 5
	StatusUnavailableForLegalReasons    = 451 // RFC 7725, 3
	StatusInternalServerError           = 500 // RFC 7231, 6.6.1
	StatusNotImplemented                = 501 // RFC 7231, 6.6.2
	StatusBadGateway                    = 502 // RFC 7231, 6.6.3
	StatusServiceUnavailable            = 503 // RFC 7231, 6.6.4
	StatusGatewayTimeout                = 504 // RFC 7231, 6.6.5
	StatusHTTPVersionNotSupported       = 505 // RFC 7231, 6.6.6
	StatusVariantAlsoNegotiates         = 506 // RFC 2295, 8.1
	StatusInsufficientStorage           = 507 // RFC 4918, 11.5
	StatusLoopDetected                  = 508 // RFC 5842, 7.2
	StatusNotExtended                   = 510 // RFC 2774, 7
	StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
)

HTTP status codes were copied from net/http.

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"
	HeaderFeaturePolicy                   = "Feature-Policy"
	HeaderPublicKeyPins                   = "Public-Key-Pins"
	HeaderPublicKeyPinsReportOnly         = "Public-Key-Pins-Report-Only"
	HeaderStrictTransportSecurity         = "Strict-Transport-Security"
	HeaderUpgradeInsecureRequests         = "Upgrade-Insecure-Requests"
	HeaderXContentTypeOptions             = "X-Content-Type-Options"
	HeaderXDownloadOptions                = "X-Download-Options"
	HeaderXFrameOptions                   = "X-Frame-Options"
	HeaderXPoweredBy                      = "X-Powered-By"
	HeaderXXSSProtection                  = "X-XSS-Protection"
	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 (
	CachePrivate        = "private"
	CachePublic         = "public"
	CacheNoStore        = "no-store"
	CacheNoCache        = "no-cache"
	CacheNoTransform    = "no-transform"
	CacheMustUnderstand = "must-understand"
	CacheImmutable      = "immutable"
)

Cache control headers

Variables

View Source
var (
	Any func(request *Request) error
)

Functions

func All

func All(path string, handlers ...Handler)

All : https://fiber.wiki/application#http-methods

func Connect

func Connect(path string, handlers ...Handler) fiber.Router

Connect : https://fiber.wiki/application#http-methods

func Delete

func Delete(path string, handlers ...Handler) fiber.Router

Delete : https://fiber.wiki/application#http-methods

func DoMigration

func DoMigration() error

func Dump

func Dump(v any)

func Get

func Get(path string, handlers ...Handler) fiber.Router

Get : https://fiber.wiki/application#http-methods

func GetDBO

func GetDBO() *gorm.DB

GetDBO return database object instance

func GetFiber

func GetFiber() *fiber.App

GetFiber return fiber instance

func GetModel

func GetModel(name string) *schema.Model

func Group

func Group(path string, handlers ...Middleware) *group

Group is used for Routes with common prefix to define a new sub-router with optional middleware.

func Head(path string, handlers ...Handler) fiber.Router

Head : https://fiber.wiki/application#http-methods

func Models

func Models() []schema.Model

func Options

func Options(path string, handlers ...Handler) fiber.Router

Options : https://fiber.wiki/application#http-methods

func Patch

func Patch(path string, handlers ...Handler) fiber.Router

Patch : https://fiber.wiki/application#http-methods

func Post

func Post(path string, handlers ...Handler) fiber.Router

Post : https://fiber.wiki/application#http-methods

func Put

func Put(path string, handlers ...Handler) fiber.Router

Put : https://fiber.wiki/application#http-methods

func Redirect

func Redirect(path, to string, code ...int)

Redirect redirects a path to another

func RedirectPermanent

func RedirectPermanent(path, to string)

RedirectPermanent redirects a path to another with code 301

func RedirectTemporary

func RedirectTemporary(path, to string)

RedirectTemporary redirects a path to another with code 302

func Repr

func Repr(v any) string

func Run

func Run()

Run start EVO Server

func SetUserInterface

func SetUserInterface(v UserInterface)

func Setup

func Setup()

Setup set up the EVO app

func Shutdown

func Shutdown() error

Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open listeners and then waiting indefinitely for all connections to return to idle and then shut down.

When Shutdown is called, Serve, ListenAndServe, and ListenAndServeTLS immediately return nil. Make sure the program doesn't exit and waits instead for Shutdown to return.

Shutdown does not close keepalive connections so its recommended to set ReadTimeout to something else than 0.

func Trace

func Trace(path string, handlers ...Handler) fiber.Router

Trace : https://fiber.wiki/application#http-methods

func Use

func Use(path string, middleware Middleware) fiber.Router

Use registers a middleware route. Middleware matches requests beginning with the provided prefix. Providing a prefix is optional, it defaults to "/"

Types

type Attributes

type Attributes map[string]any

func (Attributes) Get

func (a Attributes) Get(key string) generic.Value

func (Attributes) Has

func (a Attributes) Has(key string) bool

type CacheControl

type CacheControl struct {
	Duration      time.Duration
	Key           string
	ExposeHeaders bool
}

type DatabaseConfig

type DatabaseConfig struct {
	// Enabled enables the database connection
	Enabled bool `description:"Enabled database" default:"false" json:"enabled" yaml:"enabled"`

	// Type of database. mysql,mssql,sqlite
	Type string `description:"Database engine" default:"sqlite" json:"type" yaml:"type"`

	// Username indicates username of the database
	Username string `description:"Username" default:"root" json:"username" yaml:"username"`

	// Password indicates password of the database
	Password string `description:"Password" default:"" json:"password" yaml:"password"`

	// Server is the path of server or sqlite file path
	Server string `description:"Server" default:"127.0.0.1:3306" json:"server" yaml:"server"`

	// Cache if is enabled, it will cache the constructed queries to save process time
	Cache string `description:"Enabled query cache" default:"false" json:"cache" yaml:"cache"`

	// Debug level indicates verbosity of the logging level. 1:silent 2:warn 3:error 4:info
	Debug int `description:"Debug level (1-4)" default:"3" params:"{\"min\":1,\"max\":4}" json:"debug" yaml:"debug"`

	// Database indicates name of the database
	Database string `description:"Database Name" default:"" json:"database" yaml:"database"`

	// SSLMode enables support over ssl
	SSLMode string `description:"SSL Mode (required by some DBMS)" default:"false" json:"ssl-mode" yaml:"ssl-mode"`

	// Params will pass extra parameter to connection string
	Params string `description:"Extra connection string parameters" default:"" json:"params" yaml:"params"`

	// MaxOpenConns indicates how many concurrent connections are allowed
	MaxOpenConns int `description:"Max pool connections" default:"100" json:"max-open-connections" yaml:"max-open-connections"`

	// MaxIdleConns indicates how many concurrent idle connections are allowed
	MaxIdleConns int `description:"Max idle connections in pool" default:"10" json:"max-idle-connections" yaml:"max-idle-connections"`

	// MaxIdleConns indicates for how long a connection could be idle without being close by server
	ConnMaxLifTime time.Duration `description:"Max connection lifetime" default:"1h" json:"connection-max-lifetime" yaml:"connection-max-lifetime"`

	// SlowQueryThreshold defines the threshold duration for query execution. If the query
	// takes longer than this value, the driver will issue a warning.
	SlowQueryThreshold time.Duration `description:"Slow query threshold" default:"500ms" json:"slow_query_threshold" yaml:"slow-query-threshold"`
}

type DefaultUserInterface

type DefaultUserInterface struct{}

func (DefaultUserInterface) Anonymous

func (d DefaultUserInterface) Anonymous() bool

func (DefaultUserInterface) Attributes

func (d DefaultUserInterface) Attributes() Attributes

func (DefaultUserInterface) FromRequest

func (d DefaultUserInterface) FromRequest(request *Request) UserInterface

func (DefaultUserInterface) GetEmail

func (d DefaultUserInterface) GetEmail() string

func (DefaultUserInterface) GetFirstName

func (d DefaultUserInterface) GetFirstName() string

func (DefaultUserInterface) GetFullName

func (d DefaultUserInterface) GetFullName() string

func (DefaultUserInterface) GetLastName

func (d DefaultUserInterface) GetLastName() string

func (DefaultUserInterface) HasPermission

func (d DefaultUserInterface) HasPermission(permission string) bool

func (DefaultUserInterface) ID

func (DefaultUserInterface) Interface

func (d DefaultUserInterface) Interface() interface{}

func (DefaultUserInterface) UUID

func (d DefaultUserInterface) UUID() string

type HTTPConfig

type HTTPConfig struct {
	Host string `description:"host listening interface" default:"0.0.0.0" json:"host" yaml:"host"`
	Port string `description:"port" default:"8080" json:"port" yaml:"port"`

	// When set to true, this will spawn multiple Go processes listening on the same port.
	//
	// Default: false
	Prefork bool `` /* 143-byte string literal not displayed */

	// Enables the "Server: value" HTTP header.
	//
	// Default: ""
	ServerHeader string `description:"Enables the \"Server: value\" HTTP header." default:"EVO NG" yaml:"server_header" json:"server_header"`

	// When set to true, the router treats "/foo" and "/foo/" as different.
	// By default this is disabled and both "/foo" and "/foo/" will execute the same handler.
	//
	// Default: false
	StrictRouting bool `` /* 138-byte string literal not displayed */

	// When set to true, enables case sensitive routing.
	// E.g. "/FoO" and "/foo" are treated as different routes.
	// By default this is disabled and both "/FoO" and "/foo" will execute the same handler.
	//
	// Default: false
	CaseSensitive bool `description:"When set to true, enables case sensitive routing." default:"false" yaml:"case_sensitive" json:"case_sensitive"`

	// When set to true, this relinquishes the 0-allocation promise in certain
	// cases in order to access the handler values (e.g. request bodies) in an
	// immutable fashion so that these values are available even if you return
	// from handler.
	//
	// Default: false
	Immutable bool `` /* 179-byte string literal not displayed */

	// When set to true, converts all encoded characters in the route back
	// before setting the path for the context, so that the routing,
	// the returning of the current url from the context `ctx.Path()`
	// and the paramters `ctx.Params(%key%)` with decoded characters will work
	//
	// Default: false
	UnescapePath bool `` /* 179-byte string literal not displayed */

	// Enable or disable ETag header generation, since both weak and strong etags are generated
	// using the same hashing method (CRC-32). Weak ETags are the default when enabled.
	//
	// Default: false
	ETag bool `description:"Enable or disable ETag header generation" default:"false" yaml:"etag" json:"etag"`

	// Max body size that the server accepts.
	// -1 will decline any body size
	//
	// Default: 4 * 1024 * 1024
	BodyLimit int `` /* 135-byte string literal not displayed */

	// Maximum number of concurrent connections.
	//
	// Default: 256 * 1024
	Concurrency int `description:"Maximum number of concurrent connections." default:"1024" yaml:"concurrency" json:"concurrency"`

	// The amount of time allowed to read the full request including body.
	// It is reset after the request handler has returned.
	// The connection's read deadline is reset when the connection opens.
	//
	// Default: unlimited
	ReadTimeout time.Duration `` /* 134-byte string literal not displayed */

	// The maximum duration before timing out writes of the response.
	// It is reset after the request handler has returned.
	//
	// Default: unlimited
	WriteTimeout time.Duration `` /* 131-byte string literal not displayed */

	// 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.
	//
	// Default: unlimited
	IdleTimeout time.Duration `` /* 149-byte string literal not displayed */

	// 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: 4096
	ReadBufferSize int `description:"Per-connection buffer size for requests' reading." default:"8kb" yaml:"read_buffer_size" json:"read_buffer_size"`

	// Per-connection buffer size for responses' writing.
	//
	// Default: 4096
	WriteBufferSize int `` /* 128-byte string literal not displayed */

	// CompressedFileSuffix adds suffix to the original file name and
	// tries saving the resulting compressed file under the new file name.
	//
	// Default: ".fiber.gz"
	CompressedFileSuffix string `` /* 222-byte string literal not displayed */

	// ProxyHeader will enable c.IP() to return the value of the given header key
	// By default c.IP() will return the Remote IP from the TCP connection
	// This property can be useful if you are behind a load balancer: X-Forwarded-*
	// NOTE: headers are easily spoofed and the detected IP addresses are unreliable.
	//
	// Default: ""
	ProxyHeader string `` /* 154-byte string literal not displayed */

	// GETOnly rejects all non-GET requests if set to true.
	// This option is useful as anti-DoS protection for servers
	// accepting only GET requests. The request size is limited
	// by ReadBufferSize if GETOnly is set.
	//
	// Default: false
	GETOnly bool `description:"GETOnly rejects all non-GET requests if set to true." default:"false" yaml:"get_only" json:"get_only"`

	// When set to true, disables keep-alive connections.
	// The server will close incoming connections after sending the first response to client.
	//
	// Default: false
	DisableKeepalive bool `` /* 130-byte string literal not displayed */

	// When set to true, causes the default date header to be excluded from the response.
	//
	// Default: false
	DisableDefaultDate bool `` /* 168-byte string literal not displayed */

	// When set to true, causes the default Content-Type header to be excluded from the response.
	//
	// Default: false
	DisableDefaultContentType bool `` /* 192-byte string literal not displayed */

	// When set to true, disables header normalization.
	// By default all header names are normalized: conteNT-tYPE -> Content-Type.
	//
	// Default: false
	DisableHeaderNormalizing bool `` /* 146-byte string literal not displayed */

	// 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%.
	//
	// Default: false
	ReduceMemoryUsage bool `` /* 149-byte string literal not displayed */

	// 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 `description:"Known networks are tcp, tcp4 (IPv4-only), tcp6 (IPv6-only)" default:"tcp4" yaml:"network" json:"network"`

	// If set to true, will print all routes with their method, path and handler.
	// Default: false
	EnablePrintRoutes bool `` /* 158-byte string literal not displayed */
}

type Handler

type Handler func(request *Request) any

type Middleware

type Middleware func(request *Request) error

type Model

type Model struct {
	ID        uint       `json:"id" gorm:"primary_key"`
	CreatedAt time.Time  `json:"created_at"`
	UpdatedAt time.Time  `json:"updated_at"`
	DeletedAt *time.Time `json:"deleted_at" sql:"index"`
}

type Request

type Request struct {
	Context      *fiber.Ctx
	Response     Response
	CacheControl *CacheControl

	UserInterface *UserInterface
	// contains filtered or unexported fields
}

func Upgrade

func Upgrade(ctx *fiber.Ctx) *Request

func (*Request) Accepts

func (r *Request) Accepts(offers ...string) (offer string)

Accepts checks if the specified extensions or content types are acceptable.

func (*Request) AcceptsCharsets

func (r *Request) AcceptsCharsets(offers ...string) (offer string)

AcceptsCharsets checks if the specified charset is acceptable.

func (*Request) AcceptsEncodings

func (r *Request) AcceptsEncodings(offers ...string) (offer string)

AcceptsEncodings checks if the specified encoding is acceptable.

func (*Request) AcceptsLanguages

func (r *Request) AcceptsLanguages(offers ...string) (offer string)

AcceptsLanguages checks if the specified language is acceptable.

func (*Request) AppendHeader

func (r *Request) AppendHeader(field string, values ...string)

AppendHeader the specified value to the HTTP response header field. If the header is not already set, it creates the header with the specified value.

func (*Request) Attachment

func (r *Request) Attachment(name ...string)

Attachment sets the HTTP response Content-Disposition header field to attachment.

func (*Request) BaseURL

func (r *Request) BaseURL() string

BaseURL returns (protocol + host).

func (*Request) Body

func (r *Request) Body() string

Body contains the raw body submitted in a POST request.

func (*Request) BodyParser

func (r *Request) BodyParser(out any) error

BodyParser binds the request body to a struct. It supports decoding the following content types based on the Content-Type header: application/json, application/xml, application/x-www-form-urlencoded, multipart/form-data

func (*Request) BodyValue

func (r *Request) BodyValue(key string) generic.Value

BodyValue returns the first value by key from a MultipartForm or JSON Body.

func (*Request) Break

func (r *Request) Break()

func (*Request) ClearCookie

func (r *Request) ClearCookie(key ...string)

ClearCookie expires a specific cookie by key. If no key is provided it expires all cookies.

func (*Request) ContentType

func (r *Request) ContentType() string

ContentType returns request content type

func (*Request) Cookie

func (r *Request) Cookie(key string) (value string)

Cookie is used for getting a cookie value by key

func (*Request) Download

func (r *Request) Download(file string, name ...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 (*Request) Error

func (r *Request) Error(err any, code ...int) bool

func (*Request) Form

func (r *Request) Form() (url.Values, error)

Form.

func (*Request) FormFile

func (r *Request) FormFile(key string) (*multipart.FileHeader, error)

FormFile returns the first file by key from a MultipartForm.

func (*Request) FormValue

func (r *Request) FormValue(key string) generic.Value

FormValue returns the first value by key from a MultipartForm.

func (*Request) Format

func (r *Request) Format(body any) error

Format performs content-negotiation on the Accept HTTP header. It uses Accepts to select a proper format. If the header is not specified or there is no proper format, text/plain is used.

func (*Request) Fresh

func (r *Request) Fresh() bool

Fresh not implemented yet

func (*Request) Get

func (r *Request) Get(key string) generic.Value

Get returns the HTTP request header specified by field. Field names are case-insensitive

func (*Request) HasError

func (r *Request) HasError() bool

func (*Request) Header

func (r *Request) Header(key string) string

func (*Request) Hostname

func (r *Request) Hostname() string

Hostname contains the hostname derived from the Host HTTP header.

func (*Request) IP

func (r *Request) IP() string

IP returns user ip

func (*Request) IPs

func (r *Request) IPs() []string

IPs returns an string slice of IP addresses specified in the X-Forwarded-For request header.

func (*Request) Is

func (r *Request) Is(extension string) (match bool)

Is returns the matching content type, if the incoming request’s Content-Type HTTP header field matches the MIME type specified by the type parameter

func (*Request) IsSecure

func (r *Request) IsSecure() bool

IsSecure returns a boolean property, that is true, if a TLS connection is established.

func (*Request) JSON

func (r *Request) JSON(data any) error

JSON converts any interface or string to JSON using Jsoniter. This method also sets the content header to application/json.

func (*Request) JSONP

func (r *Request) JSONP(json any, callback ...string) error

JSONP sends a JSON response with JSONP support. This method is identical to JSON, except that it opts-in to JSONP callback support. By default, the callback name is simply callback.

func (r *Request) Links(link ...string)

Links joins the links followed by the property to populate the response’s Link HTTP header field.

func (*Request) Locals

func (r *Request) Locals(key string, value ...any) (val any)

Locals makes it possible to pass any values under string keys scoped to the request and therefore available to all following routes that match the request.

func (*Request) Location

func (r *Request) Location(path string)

Location sets the response Location HTTP header to the specified path parameter.

func (*Request) Method

func (r *Request) Method(override ...string) string

Method contains a string corresponding to the HTTP method of the request: GET, POST, PUT and so on.

func (*Request) MultipartForm

func (r *Request) MultipartForm() (*multipart.Form, error)

MultipartForm parse form entries from binary. This returns a map[string][]string, so given a key the value will be a string slice.

func (*Request) Next

func (r *Request) Next() error

Next executes the next method in the stack that matches the current route. You can pass an optional error for custom error handling.

func (*Request) OriginalURL

func (r *Request) OriginalURL() string

OriginalURL contains the original request URL.

func (*Request) Param

func (r *Request) Param(key string) generic.Value

Param is used to get the route parameters. Defaults to empty string "", if the param doesn't exist.

func (*Request) Params

func (r *Request) Params() map[string]string

Params return map of parameters in url

func (*Request) ParseJsonBody

func (r *Request) ParseJsonBody() *gjson.Result

ParseJsonBody returns parsed JSON Body using gjson.

func (*Request) Path

func (r *Request) Path(override ...string) string

Path returns the path part of the request URL. Optionally, you could override the path.

func (*Request) Protocol

func (r *Request) Protocol() string

Protocol contains the request protocol string: http or https for TLS requests.

func (*Request) PushError

func (r *Request) PushError(err any, code ...int) bool

func (*Request) Query

func (r *Request) Query(key string) (value generic.Value)

Query returns the query string parameter in the url.

func (*Request) QueryString

func (r *Request) QueryString() string

QueryString returns url query string.

func (*Request) Redirect

func (r *Request) Redirect(path string, status ...int) error

Redirect to the URL derived from the specified path, with specified status. If status is not specified, status defaults to 302 Found

func (*Request) ReqHeaders

func (r *Request) ReqHeaders() map[string]string

func (*Request) RespHeaders

func (r *Request) RespHeaders() map[string]string

func (*Request) RestartRouting

func (r *Request) RestartRouting() error

func (*Request) Route

func (r *Request) Route(name string, params ...any) string

Route generate route for named routes

func (*Request) SaveFile

func (r *Request) SaveFile(fileheader *multipart.FileHeader, path string) error

SaveFile saves any multipart file to disk.

func (*Request) Send

func (r *Request) Send(body string) error

Send sets the HTTP response body. The Send body can be of any type.

func (*Request) SendBytes

func (r *Request) SendBytes(body []byte) error

SendBytes sets the HTTP response body for []byte types This means no type assertion, recommended for faster performance

func (*Request) SendFile

func (r *Request) SendFile(file string, noCompression ...bool) error

SendFile transfers the file from the given path. The file is compressed by default Sets the Content-Type response HTTP header field based on the filenames extension.

func (*Request) SendHTML

func (r *Request) SendHTML(body any)

Send sets the HTML response body. The Send body can be of any type.

func (*Request) SendStatus

func (r *Request) SendStatus(status int) error

SendStatus sets the HTTP status code and if the response body is empty, it sets the correct status message in the body.

func (*Request) SendString

func (r *Request) SendString(body string) error

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

func (*Request) Set

func (r *Request) Set(key string, val string)

Set sets the response’s HTTP header field to the specified key, value.

func (*Request) SetCacheControl

func (r *Request) SetCacheControl(t time.Duration, headers ...string)

func (*Request) SetCookie

func (r *Request) SetCookie(key string, val any, params ...any)

SetCookie set cookie with given name,value and optional params (wise function)

func (*Request) SetHeader

func (r *Request) SetHeader(key, val string)

func (*Request) SetRawCookie

func (r *Request) SetRawCookie(cookie *outcome.Cookie)

SetRawCookie sets a cookie by passing a cookie struct

func (*Request) Stale

func (r *Request) Stale() bool

Stale is not implemented yet, pull requests are welcome!

func (*Request) Status

func (r *Request) Status(status int) *Request

Status sets the HTTP status for the response. This method is chainable.

func (*Request) Subdomains

func (r *Request) Subdomains(offset ...int) []string

Subdomains returns a string slive of subdomains in the domain name of the request. The subdomain offset, which defaults to 2, is used for determining the beginning of the subdomain segments.

func (*Request) Type

func (r *Request) Type(ext string) *Request

Type sets the Content-Type HTTP header to the MIME type specified by the file extension.

func (*Request) URL

func (r *Request) URL() *URL

func (*Request) User

func (r *Request) User() UserInterface

func (*Request) UserAgent

func (r *Request) UserAgent() string

UserAgent returns request useragent

func (*Request) Var

func (r *Request) Var(key string, value ...any) generic.Value

func (*Request) Vary

func (r *Request) Vary(fields ...string)

Vary adds the given header field to the Vary response header. This will append the header, if not already listed, otherwise leaves it listed in the current location.

func (*Request) Write

func (r *Request) Write(body any)

Write appends any input to the HTTP body response.

func (*Request) WriteResponse

func (r *Request) WriteResponse(resp ...any)

func (*Request) XHR

func (r *Request) XHR() bool

XHR returns a Boolean property, that is true, if the request’s X-Requested-With header field is XMLHttpRequest, indicating that the request was issued by a client library (such as jQuery).

type Response

type Response struct {
	Success bool     `json:"success"`
	Error   []string `json:"errors,omitempty"`
	Data    any      `json:"data,omitempty"`
}

func (Response) HasError

func (response Response) HasError() bool

type URL

type URL struct {
	Query       url.Values
	QueryString string
	Host        string
	Scheme      string
	Path        string
	Raw         string
}

func (*URL) Set

func (u *URL) Set(key string, value any) *URL

func (*URL) String

func (u *URL) String() string

type UserInterface

type UserInterface interface {
	GetFirstName() string
	GetLastName() string
	GetFullName() string
	GetEmail() string
	UUID() string
	ID() uint64
	Anonymous() bool
	HasPermission(permission string) bool
	Attributes() Attributes
	Interface() interface{}
	FromRequest(request *Request) UserInterface
}
var UserInterfaceInstance UserInterface = DefaultUserInterface{}

Directories

Path Synopsis
lib
async
Package stream provides a concurrent, ordered stream implementation.
Package stream provides a concurrent, ordered stream implementation.
db
dot
frm
Package frm decodes HTTP form and query parameters.
Package frm decodes HTTP form and query parameters.
is
log
tpl
try
version
Version normalizer and comparison library for go, heavy based on PHP version_compare function and Version comparsion libs from Composer (https://github.com/composer/composer) PHP project
Version normalizer and comparison library for go, heavy based on PHP version_compare function and Version comparsion libs from Composer (https://github.com/composer/composer) PHP project

Jump to

Keyboard shortcuts

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