evo

package module
v2.0.0-...-2d9c7e5 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2026 License: MIT Imports: 42 Imported by: 7

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

Libraries

EVO Framework includes a comprehensive set of libraries in the lib directory:

  • Application - Application management
  • Args - Command-line argument handling
  • Async - Asynchronous operations
  • Build - Build utilities
  • Connectors - External system connectors
  • Curl - HTTP client functionality
  • Date - Date and time utilities
  • DB - Database operations
  • Dot - Dot notation for accessing nested data
  • Errors - Error handling
  • Frm - Form handling
  • Generic - Generic data structures
  • Gpath - Path manipulation
  • Is - Type checking utilities
  • JSON - JSON handling
  • Log - Logging system
  • Memo - Memoization and caching
  • Model - Data modeling
  • Outcome - Function result handling
  • Panics - Panic handling
  • Ptr - Pointer utilities
  • Pubsub - Publish-subscribe pattern
  • Reflections - Reflection utilities
  • Scheduler - Task scheduling
  • Serializer - Data serialization
  • Settings - Configuration management
  • Storage - Storage interfaces
  • Stract - Structured data handling
  • Text - Text manipulation
  • Tpl - Template system
  • Try - Error handling with try/catch pattern
  • Validation - Data validation
  • Version - Version management

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:

MySQL:

package main

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

func main() {
    evo.Setup(mysql.Driver{})
    evo.Run()
}

PostgreSQL:

package main

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

func main() {
    evo.Setup(pgsql.Driver{})
    evo.Run()
}

Documentation

Index

Examples

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
)
View Source
var Application *application.App

Functions

func All

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

All registers handlers for all HTTP methods on the given path.

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 GetDB

func GetDB(ctx ...context.Context) *gorm.DB

GetDB returns a database instance with context for proper context propagation. This is the preferred method for obtaining database connections.

func GetDBO

func GetDBO(ctx ...context.Context) *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 GetRoutes

func GetRoutes(filterMiddleware ...bool) []fiber.Route

GetRoutes returns all registered routes. Pass true to exclude middleware-only routes.

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 OnHealthCheck

func OnHealthCheck(fn HealthCheckFunc)

OnHealthCheck registers a health check function that will be called on /health endpoint Health checks determine if the application is running and able to handle requests

Example:

evo.OnHealthCheck(func() error {
    if appIsHealthy() {
        return nil
    }
    return fmt.Errorf("app is unhealthy")
})
Example

ExampleOnHealthCheck demonstrates how to register a health check

// Register a health check that always passes
OnHealthCheck(func() error {
	// Check if application is healthy
	// Return nil if healthy, error otherwise
	return nil
})

// Register multiple health checks
OnHealthCheck(func() error {
	// Check database connection
	// if db.Ping() != nil {
	//     return fmt.Errorf("database not responding")
	// }
	return nil
})

OnHealthCheck(func() error {
	// Check external service
	// if !externalService.IsAlive() {
	//     return fmt.Errorf("external service unreachable")
	// }
	return nil
})

fmt.Println("Health checks registered")
Output:

Health checks registered

func OnReadyCheck

func OnReadyCheck(fn HealthCheckFunc)

OnReadyCheck registers a readiness check function that will be called on /ready endpoint Readiness checks determine if the application is ready to receive traffic (e.g., database connections established, caches warmed up)

Example:

evo.OnReadyCheck(func() error {
    if db.Ping() == nil {
        return nil
    }
    return fmt.Errorf("database not ready")
})
Example

ExampleOnReadyCheck demonstrates how to register a readiness check

// Register readiness check for database
OnReadyCheck(func() error {
	// Check if database is ready
	// if !db.IsReady() {
	//     return fmt.Errorf("database not ready")
	// }
	return nil
})

// Register readiness check for cache
OnReadyCheck(func() error {
	// Check if cache is ready
	// if !cache.IsWarmedUp() {
	//     return fmt.Errorf("cache not warmed up")
	// }
	return nil
})

fmt.Println("Readiness checks registered")
Output:

Readiness checks registered

func OnShutdown

func OnShutdown(fn func())

OnShutdown registers fn to be called during graceful shutdown, before the HTTP server stops accepting connections. Hooks are called in the order they were registered. Safe to call from any goroutine at any time before shutdown.

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

func Register(applications ...application.Application) *application.App

func Repr

func Repr(v any) string

func Run

func Run() error

Run start EVO Server Returns an error if the server fails to start, allowing for graceful shutdown.

func SetUserInterface

func SetUserInterface(v UserInterface)

func Setup

func Setup(params ...any) error

Setup set up the EVO app. Optional params: pass a db.Driver to select the database driver (e.g. pgsql.Driver{} or mysql.Driver{}). Returns an error if setup fails instead of calling log.Fatal, allowing for graceful error handling.

func Shutdown

func Shutdown() error

Shutdown gracefully shuts down the server without interrupting any active connections. It first runs all hooks registered via OnShutdown, then stops the HTTP server.

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 ShutdownWithContext

func ShutdownWithContext(ctx context.Context) error

ShutdownWithContext shuts down the server, forcing close when ctx is done.

func ShutdownWithTimeout

func ShutdownWithTimeout(timeout time.Duration) error

ShutdownWithTimeout gracefully shuts down the server. If the timeout is exceeded it forcefully closes any remaining active connections.

func Static

func Static(path string, dir string, config ...static.Config) fiber.Router

Static serves files from the file system

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,postgres,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"`

	// Schema name (PostgreSQL only, defaults to 'public')
	Schema string `description:"Database schema (PostgreSQL only)" default:"public" json:"schema" yaml:"schema"`

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

type HealthCheckFunc func() error

HealthCheckFunc is a function that performs a health or readiness check It should return nil if the check passes, or an error describing the problem

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) AcceptEncoding

func (r *Request) AcceptEncoding() string

AcceptEncoding returns the single best-match value from the Accept-Encoding header.

func (*Request) AcceptLanguage

func (r *Request) AcceptLanguage() string

AcceptLanguage returns the single best-match value from the Accept-Language header.

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) AcceptsEventStream

func (r *Request) AcceptsEventStream() bool

AcceptsEventStream reports whether the Accept header allows text/event-stream.

func (*Request) AcceptsHTML

func (r *Request) AcceptsHTML() bool

AcceptsHTML reports whether the Accept header allows text/html.

func (*Request) AcceptsJSON

func (r *Request) AcceptsJSON() bool

AcceptsJSON reports whether the Accept header allows application/json.

func (*Request) AcceptsLanguages

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

AcceptsLanguages checks if the specified language is acceptable.

func (*Request) AcceptsLanguagesExtended

func (r *Request) AcceptsLanguagesExtended(offers ...string) string

AcceptsLanguagesExtended checks if any of the offered languages is acceptable using RFC 4647 extended filtering (subtag matching).

func (*Request) AcceptsXML

func (r *Request) AcceptsXML() bool

AcceptsXML reports whether the Accept header allows application/xml or text/xml.

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) AutoFormat

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

AutoFormat performs content-negotiation on the Accept header and sends the body in the best matching format (JSON, XML, text, etc.).

func (*Request) BaseURL

func (r *Request) BaseURL() string

BaseURL returns (protocol + host).

func (*Request) Bind

func (r *Request) Bind() *fiber.Bind

Bind returns the Fiber v3 Bind helper for unified request binding. Use it to bind body, query, headers, cookies, URI params into structs:

var body MyDTO
if err := r.Bind().Body(&body); err != nil { ... }
if err := r.Bind().Query(&q); err != nil { ... }

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) BodyRaw

func (r *Request) BodyRaw() []byte

BodyRaw returns the raw (undecoded) request body bytes. Unlike Body(), this skips decompression.

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) CBOR

func (r *Request) CBOR(data any, ctype ...string) error

CBOR serialises data to CBOR binary format and sends it with Content-Type application/cbor.

func (*Request) Charset

func (r *Request) Charset() string

Charset returns the charset parameter from the Content-Type header.

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) Debug

func (r *Request) Debug() string

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) Drop

func (r *Request) Drop() error

Drop closes the underlying connection without sending any response headers or body. Useful for DDoS mitigation.

func (*Request) End

func (r *Request) End() error

End signals the end of an SSE (Server-Sent Events) stream.

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) FullPath

func (r *Request) FullPath() string

FullPath returns the matched route pattern including any group prefixes, e.g. "/users/:id". Use Path() to get the actual request path.

func (*Request) FullURL

func (r *Request) FullURL() string

FullURL returns the full request URL (protocol + host + path + query).

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) GetRespHeader

func (r *Request) GetRespHeader(key string, defaultValue ...string) string

GetRespHeader returns the value of a response header that has already been set. An optional defaultValue is returned when the header is absent.

func (*Request) HasBody

func (r *Request) HasBody() bool

HasBody returns true if the request declares a body via Content-Length, Transfer-Encoding, or already-buffered payload data.

func (*Request) HasError

func (r *Request) HasError() bool

func (*Request) HasHeader

func (r *Request) HasHeader(key string) bool

HasHeader reports whether the request includes a header with the given key.

func (*Request) Header

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

func (*Request) Host

func (r *Request) Host() string

Host returns the raw Host header value, including the port when present. Use Hostname() to get only the host part without the port.

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) IsForm

func (r *Request) IsForm() bool

IsForm reports whether the request Content-Type is application/x-www-form-urlencoded.

func (*Request) IsFromLocal

func (r *Request) IsFromLocal() bool

IsFromLocal returns true if the request originated from localhost.

func (*Request) IsJSON

func (r *Request) IsJSON() bool

IsJSON reports whether the request Content-Type is application/json.

func (*Request) IsMultipart

func (r *Request) IsMultipart() bool

IsMultipart reports whether the request Content-Type is multipart/form-data.

func (*Request) IsPreflight

func (r *Request) IsPreflight() bool

IsPreflight returns true if the request is a CORS preflight (OPTIONS with Origin and Access-Control-Request-Method headers).

func (*Request) IsProxyTrusted

func (r *Request) IsProxyTrusted() bool

IsProxyTrusted reports whether the remote IP falls within the configured trusted proxy ranges.

func (*Request) IsSecure

func (r *Request) IsSecure() bool

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

func (*Request) IsWebSocket

func (r *Request) IsWebSocket() bool

IsWebSocket returns true if the request contains a WebSocket upgrade handshake.

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) MediaType

func (r *Request) MediaType() string

MediaType returns the MIME type from the Content-Type header without parameters.

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) MsgPack

func (r *Request) MsgPack(data any, ctype ...string) error

MsgPack serialises data to MessagePack binary format and sends it with Content-Type application/msgpack.

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) OnResponse

func (r *Request) OnResponse(fn func(body []byte) []byte)

func (*Request) OriginalURL

func (r *Request) OriginalURL() string

OriginalURL contains the original request URL.

func (*Request) OverrideParam

func (r *Request) OverrideParam(name, value string)

OverrideParam overwrites the value of a named route parameter in-flight. Useful in middleware that rewrites routing parameters.

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) Port

func (r *Request) Port() string

Port returns the remote port of the request.

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) Queries

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

Queries returns all query parameters as a flat map[string]string.

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) Range

func (r *Request) Range(size int64) (fiber.Range, error)

Range parses the Range request header for partial-content responses. size is the total length of the resource in bytes.

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) Referer

func (r *Request) Referer() string

Referer returns the value of the Referer request header.

func (*Request) ReqHeaders

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

func (*Request) RequestID

func (r *Request) RequestID() string

RequestID returns the unique request identifier from the X-Request-Id response header (set by Fiber's RequestID middleware) or from the incoming request header.

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) SaveFileToStorage

func (r *Request) SaveFileToStorage(fileheader *multipart.FileHeader, path string, storage fiber.Storage) error

SaveFileToStorage saves a multipart upload directly into a custom Storage backend (any type that satisfies fiber.Storage).

func (*Request) Scheme

func (r *Request) Scheme() string

Scheme returns the request scheme: "http" or "https". This is an alias for Protocol().

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) SendEarlyHints

func (r *Request) SendEarlyHints(hints []string) error

SendEarlyHints sends an HTTP 103 Early Hints response with Link preload headers so that the browser can begin fetching resources before the final response is ready. hints is a slice of Link header values.

func (*Request) SendFile

func (r *Request) SendFile(file string, cfg ...fiber.SendFile) error

SendFile transfers the file from the given path. 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) SendStream

func (r *Request) SendStream(stream io.Reader, size ...int) error

SendStream sets the response body to the given io.Reader stream. The optional size argument sets the Content-Length header.

func (*Request) SendStreamWriter

func (r *Request) SendStreamWriter(streamWriter func(*bufio.Writer)) error

SendStreamWriter sets the response body to the output of a buffered writer function. The writer runs in the current goroutine; close when done.

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) SetContext

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

SetContext replaces the request's context.Context. The new context is propagated to all downstream handlers for this request.

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) WriteString

func (r *Request) WriteString(s string) (int, error)

WriteString appends a string to the response body (io.StringWriter interface).

func (*Request) Writef

func (r *Request) Writef(f string, a ...any) (int, error)

Writef appends a formatted string to the response body (fmt.Fprintf style).

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

func (*Request) XML

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

XML serialises data to XML and sends it with Content-Type application/xml.

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
ptr
settings
Package settings provides a thread-safe, multi-source configuration management system.
Package settings provides a thread-safe, multi-source configuration management system.
shutdown
Package shutdown provides a global registry for shutdown hooks.
Package shutdown provides a global registry for shutdown hooks.
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