Documentation
ΒΆ
Overview ΒΆ
Ctx represents the context of an HTTP request and response.
It provides access to the request, response, headers, query parameters, body, and other necessary attributes for handling HTTP requests.
Fields:
- Response: The HTTP response writer.
- Request: The HTTP request object.
- resStatus: The HTTP response status code.
- MoreRequests: Counter for additional requests in a batch processing scenario.
- bodyByte: The raw body content as a byte slice.
- JsonStr: The raw body content as a string.
- Headers: A map containing all request headers.
- Params: A map containing URL parameters (e.g., /users/:id β id).
- Query: A map containing query parameters (e.g., ?name=John).
- uploadFileSize: The maximum allowed upload file size in bytes.
- App: A reference to the Quick application instance.
Package quick provides a high-performance, minimalistic web framework for building web applications in Go.
This file defines constants for HTTP methods and status codes, as well as a utility function to return human-readable descriptions for status codes. These definitions ensure consistent use of HTTP standards throughout the framework.
π Quick is a flexible and extensible route manager for the Go language. It aims to be fast and performant, and 100% net/http compatible. Quick is a project under constant development and is open for collaboration, everyone is welcome to contribute. π
Package quick provides a high-performance, lightweight web framework for building modern HTTP applications in Go. It is designed for speed, efficiency, and simplicity.
Features: - Middleware support for request/response processing. - Optimized routing with low overhead. - Built-in support for JSON, XML, and form parsing. - Efficient request handling using sync.Pool for memory optimization. - Customizable response handling with structured output.
Quick is ideal for building RESTful APIs, microservices, and high-performance web applications.
Package quick provides a high-performance HTTP framework for building web applications in Go.
Quick is designed to be lightweight and efficient, offering a simplified API for handling HTTP requests, file uploads, middleware, and routing.
Features:
- Route management with support for grouped routes.
- Middleware support for request processing.
- File handling capabilities, including uploads and size validation.
- High-performance request handling using Goβs standard `net/http` package.
Qtest is an advanced HTTP testing function designed to facilitate route validation in the Quick framework.
It allows you to test simulated HTTP requests using httptest, supporting:
- MΓ©todos HTTP personalizados (GET, POST, PUT, DELETE, etc.)
- CabeΓ§alhos (Headers) personalizados.
- ParΓ’metros de Query (QueryParams).
- Corpo da RequisiΓ§Γ£o (Body).
- Cookies.
- ValidaΓ§Γ΅es embutidas para status, headers e corpo da resposta.
The Qtest function receives a QuickTestOptions structure containing the request parameters, executes the call and returns a QtestReturn object, which provides methods for analyzing and validating the result.
Index ΒΆ
- Constants
- Variables
- func MaxBytesReader(w http.ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser
- func NotFound(w http.ResponseWriter, r *http.Request)
- func SaveAll(files []*UploadedFile, destination string) error
- func StatusText(code int) string
- type App
- type Config
- type ContextBuilder
- type CorsConfig
- type Ctx
- func (c *Ctx) Accepts(acceptType string) *Ctx
- func (c *Ctx) Add(key, value string)
- func (c *Ctx) Append(key, value string)
- func (c *Ctx) Bind(v interface{}) (err error)
- func (c *Ctx) Body() []byte
- func (c *Ctx) BodyParser(v interface{}) error
- func (c *Ctx) BodyString() string
- func (c *Ctx) Byte(b []byte) (err error)
- func (c *Ctx) Ctx() context.Context
- func (c *Ctx) Del(key string)
- func (c *Ctx) File(filePath string) error
- func (c *Ctx) FormFile(fieldName string) (*UploadedFile, error)
- func (c *Ctx) FormFileLimit(limit string) error
- func (c *Ctx) FormFiles(fieldName string) ([]*UploadedFile, error)
- func (c *Ctx) FormValue(key string) string
- func (c *Ctx) FormValues() map[string][]string
- func (c *Ctx) Get(key string) string
- func (c *Ctx) GetAllContextData() map[string]any
- func (c *Ctx) GetHeader(key string) string
- func (c *Ctx) GetHeaders() http.Header
- func (c *Ctx) GetHeadersAll() map[string][]string
- func (c *Ctx) GetReqHeadersAll() map[string][]string
- func (c *Ctx) GetTraceID(nameTraceID string) (traceID string)
- func (c *Ctx) HTML(name string, data interface{}, layouts ...string) error
- func (c *Ctx) Host() string
- func (c *Ctx) IP() string
- func (c *Ctx) JSON(v interface{}) error
- func (c *Ctx) JSONIN(v interface{}, params ...string) error
- func (c *Ctx) Logger() *ContextBuilder
- func (c *Ctx) Method() string
- func (c *Ctx) MultipartForm() (*multipart.Form, error)
- func (c *Ctx) Next() error
- func (c *Ctx) OriginalURI() string
- func (c *Ctx) Param(key string) string
- func (c *Ctx) Path() string
- func (c *Ctx) QueryParam(key string) string
- func (c *Ctx) Redirect(location string, code ...int) error
- func (c *Ctx) RemoteIP() string
- func (c *Ctx) Reset(w http.ResponseWriter, r *http.Request)
- func (c *Ctx) Send(b []byte) (err error)
- func (c *Ctx) SendFile(file []byte) error
- func (c *Ctx) SendString(s string) error
- func (c *Ctx) Set(key, value string)
- func (c *Ctx) SetContext() *ContextBuilder
- func (c *Ctx) SetCtx(ctx context.Context)
- func (c *Ctx) SetStatus(status int)
- func (c *Ctx) SetTraceID(key, val string) *ContextBuilder
- func (c *Ctx) Status(status int) *Ctx
- func (c *Ctx) String(s string) error
- func (c *Ctx) XML(v interface{}) error
- type Error
- type FileInfo
- type Group
- func (g *Group) Delete(pattern string, handlerFunc HandleFunc)
- func (g *Group) Get(pattern string, handlerFunc HandleFunc)
- func (g *Group) Handle(method, pattern string, handlerFunc HandleFunc, paramExtractor any)
- func (g *Group) Options(pattern string, handlerFunc HandleFunc)
- func (g *Group) Patch(pattern string, handlerFunc HandleFunc)
- func (g *Group) Post(pattern string, handlerFunc HandleFunc)
- func (g *Group) Put(pattern string, handlerFunc HandleFunc)
- func (g *Group) Use(mw func(http.Handler) http.Handler)
- type HandleFunc
- type Handler
- type HandlerFunc
- type M
- type MiddlewareFunc
- type QTestPlus
- func (qt *QTestPlus) AssertBodyContains(expected any) error
- func (qt *QTestPlus) AssertHeader(key, expectedValue string) error
- func (qt *QTestPlus) AssertHeaderContains(key, substring string) error
- func (qt *QTestPlus) AssertHeaderHasPrefix(key, prefix string) error
- func (qt *QTestPlus) AssertHeaderHasValueInSet(key string, allowed []string) error
- func (qt *QTestPlus) AssertNoHeader(key string) error
- func (qt *QTestPlus) AssertStatus(expected int) error
- func (qt *QTestPlus) AssertString(expected string) error
- func (qt *QTestPlus) Body() []byte
- func (qt *QTestPlus) BodyStr() string
- func (qt *QTestPlus) Response() *http.Response
- func (qt *QTestPlus) StatusCode() int
- type QtestReturn
- type Quick
- func (q *Quick) Any(path string, handlerFunc HandleFunc)
- func (q *Quick) Delete(pattern string, handlerFunc HandleFunc)
- func (q *Quick) Display(scheme, addr string)
- func (q *Quick) Get(pattern string, handlerFunc HandleFunc)
- func (q *Quick) GetConfig() Config
- func (q *Quick) GetRoute() []*Route
- func (q *Quick) Group(prefix string) *Group
- func (q *Quick) Handler() http.Handler
- func (q *Quick) HandlerFunc(h HandlerFunc) http.HandlerFunc
- func (q *Quick) HandlersCount() uint32
- func (q *Quick) Head(pattern string, handlerFunc HandleFunc)
- func (q *Quick) Listen(addr string, handler ...http.Handler) error
- func (q *Quick) ListenTLS(addr, certFile, keyFile string, useHTTP2 bool, handler ...http.Handler) error
- func (q *Quick) ListenWithShutdown(addr string, handler ...http.Handler) (*http.Server, func(), error)
- func (q *Quick) Options(pattern string, handlerFunc HandleFunc)
- func (q *Quick) Patch(pattern string, handlerFunc HandleFunc)
- func (q *Quick) Post(pattern string, handlerFunc HandleFunc)
- func (q *Quick) Put(pattern string, handlerFunc HandleFunc)
- func (q Quick) Qtest(opts QuickTestOptions) (QtestReturn, error)
- func (q *Quick) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (q *Quick) Shutdown() error
- func (q *Quick) Static(route string, dirOrFS any)
- func (q *Quick) Use(mw any)
- type QuickMockCtx
- type QuickMockTestServer
- type QuickTestOptions
- type QuickTestReturn
- type Route
- type UploadedFile
- type Zeroth
Examples ΒΆ
- Ctx.Accepts
- Ctx.Append
- Ctx.Bind
- Ctx.Body
- Ctx.BodyParser
- Ctx.BodyString
- Ctx.Byte
- Ctx.File
- Ctx.FormFile
- Ctx.FormFileLimit
- Ctx.FormFiles
- Ctx.GetHeader
- Ctx.GetHeaders
- Ctx.GetHeadersAll
- Ctx.GetReqHeadersAll
- Ctx.JSON
- Ctx.JSONIN
- Ctx.Method
- Ctx.MultipartForm
- Ctx.Next
- Ctx.Param
- Ctx.Path
- Ctx.QueryParam
- Ctx.Redirect
- Ctx.RemoteIP
- Ctx.Send
- Ctx.SendFile
- Ctx.SendString
- Ctx.Set
- Ctx.Status
- Ctx.String
- Ctx.XML
- GetDefaultConfig
- Group.Delete
- Group.Get
- Group.Options
- Group.Patch
- Group.Post
- Group.Put
- Group.Use
- MaxBytesReader
- New
- QTestPlus.AssertBodyContains
- QTestPlus.AssertHeader
- QTestPlus.AssertHeaderContains
- QTestPlus.AssertHeaderHasPrefix
- QTestPlus.AssertHeaderHasValueInSet
- QTestPlus.AssertNoHeader
- QTestPlus.AssertStatus
- QTestPlus.AssertString
- QTestPlus.Body
- QTestPlus.BodyStr
- QTestPlus.Response
- QTestPlus.StatusCode
- Quick.Delete
- Quick.Get
- Quick.GetRoute
- Quick.Group
- Quick.Listen
- Quick.Options
- Quick.Patch
- Quick.Post
- Quick.Put
- Quick.Qtest
- Quick.ServeHTTP
- Quick.Shutdown
- Quick.Static
- Quick.Use
- SaveAll
- StatusText
- UploadedFile.Bytes
- UploadedFile.ContentType
- UploadedFile.FileName
- UploadedFile.Save
- UploadedFile.Size
Constants ΒΆ
const ( // MethodGet represents the HTTP GET method. MethodGet = "GET" // MethodHead represents the HTTP HEAD method. MethodHead = "HEAD" // MethodPost represents the HTTP POST method. MethodPost = "POST" // MethodPut represents the HTTP PUT method. MethodPut = "PUT" // MethodPatch represents the HTTP PATCH method (RFC 5789). MethodPatch = "PATCH" // MethodDelete represents the HTTP DELETE method. MethodDelete = "DELETE" // MethodConnect represents the HTTP CONNECT method. MethodConnect = "CONNECT" // MethodOptions represents the HTTP OPTIONS method. MethodOptions = "OPTIONS" // MethodTrace represents the HTTP TRACE method. MethodTrace = "TRACE" )
const ( // StatusContinue indicates that the client should continue with its request. StatusContinue = 100 // RFC 9110, 15.2.1 // StatusSwitchingProtocols indicates that the server is switching protocols as requested. StatusSwitchingProtocols = 101 // RFC 9110, 15.2.2 // StatusProcessing indicates that the server has received the request but has not completed processing. StatusProcessing = 102 // RFC 2518, 10.1 // StatusEarlyHints provides early hints to help a client start preloading resources. StatusEarlyHints = 103 // RFC 8297 // StatusOK indicates that the request has succeeded. StatusOK = 200 // RFC 9110, 15.3.1 // StatusCreated indicates that the request has been fulfilled and a new resource is created. StatusCreated = 201 // RFC 9110, 15.3.2 // StatusAccepted indicates that the request has been accepted for processing but is not complete. StatusAccepted = 202 // RFC 9110, 15.3.3 // StatusNonAuthoritativeInfo indicates that the response contains information from another source. StatusNonAuthoritativeInfo = 203 // RFC 9110, 15.3.4 // StatusNoContent indicates that the server successfully processed the request but has no content to return. StatusNoContent = 204 // RFC 9110, 15.3.5 // StatusResetContent indicates that the client should reset the document view. StatusResetContent = 205 // RFC 9110, 15.3.6 // StatusPartialContent indicates that only part of the requested resource is returned. StatusPartialContent = 206 // RFC 9110, 15.3.7 // StatusMultiStatus indicates that multiple status codes might be returned. StatusMultiStatus = 207 // RFC 4918, 11.1 // StatusAlreadyReported indicates that the request has already been reported in a previous response. StatusAlreadyReported = 208 // RFC 5842, 7.1 // StatusIMUsed indicates that the response is a result of an instance manipulation. StatusIMUsed = 226 // RFC 3229, 10.4.1 // StatusMultipleChoices indicates that multiple possible resources could be returned. StatusMultipleChoices = 300 // RFC 9110, 15.4.1 // StatusMovedPermanently indicates that the resource has moved permanently to a new URI. StatusMovedPermanently = 301 // RFC 9110, 15.4.2 // StatusFound indicates that the requested resource has been temporarily moved. StatusFound = 302 // RFC 9110, 15.4.3 // StatusSeeOther indicates that the response is available at a different URI. StatusSeeOther = 303 // RFC 9110, 15.4.4 // StatusNotModified indicates that the resource has not been modified since the last request. StatusNotModified = 304 // RFC 9110, 15.4.5 // StatusUseProxy indicates that the requested resource must be accessed through a proxy. StatusUseProxy = 305 // RFC 9110, 15.4.6 // StatusTemporaryRedirect indicates that the request should be repeated with a different URI. StatusTemporaryRedirect = 307 // RFC 9110, 15.4.8 // StatusPermanentRedirect indicates that the resource has been permanently moved. StatusPermanentRedirect = 308 // RFC 9110, 15.4.9 // StatusBadRequest indicates that the server cannot process the request due to client error. StatusBadRequest = 400 // RFC 9110, 15.5.1 StatusUnauthorized = 401 // RFC 9110, 15.5.2 // StatusPaymentRequired is reserved for future use (typically related to digital payments). StatusPaymentRequired = 402 // RFC 9110, 15.5.3 // StatusForbidden indicates that the request is valid, but the server is refusing to process it. StatusForbidden = 403 // RFC 9110, 15.5.4 // StatusNotFound indicates that the requested resource could not be found. StatusNotFound = 404 // RFC 9110, 15.5.5 // StatusMethodNotAllowed indicates that the request method is not allowed for the resource. StatusMethodNotAllowed = 405 // RFC 9110, 15.5.6 // StatusNotAcceptable indicates that the server cannot return a response that meets the client's requirements. StatusNotAcceptable = 406 // RFC 9110, 15.5.7 // StatusProxyAuthRequired indicates that authentication is required for a proxy server. StatusProxyAuthRequired = 407 // RFC 9110, 15.5.8 // StatusRequestTimeout indicates that the server timed out waiting for the request. StatusRequestTimeout = 408 // RFC 9110, 15.5.9 // StatusConflict indicates that the request could not be completed due to a conflict with the current resource state. StatusConflict = 409 // RFC 9110, 15.5.10 // StatusGone indicates that the requested resource is no longer available and will not return. StatusGone = 410 // RFC 9110, 15.5.11 // StatusLengthRequired indicates that the request must include a valid `Content-Length` header. StatusLengthRequired = 411 // RFC 9110, 15.5.12 // StatusPreconditionFailed indicates that a precondition in the request headers was not met. StatusPreconditionFailed = 412 // RFC 9110, 15.5.13 // StatusRequestEntityTooLarge indicates that the request body is too large for the server to process. StatusRequestEntityTooLarge = 413 // RFC 9110, 15.5.14 // StatusRequestURITooLong indicates that the request URI is too long for the server to process. StatusRequestURITooLong = 414 // RFC 9110, 15.5.15 // StatusUnsupportedMediaType indicates that the request body format is not supported by the server. StatusUnsupportedMediaType = 415 // RFC 9110, 15.5.16 // StatusRequestedRangeNotSatisfiable indicates that the range specified in the request cannot be fulfilled. StatusRequestedRangeNotSatisfiable = 416 // RFC 9110, 15.5.17 // StatusExpectationFailed indicates that the server cannot meet the expectations set in the request headers. StatusExpectationFailed = 417 // RFC 9110, 15.5.18 // StatusTeapot is an Easter egg from RFC 9110, originally from April Fools' Day (RFC 2324). StatusTeapot = 418 // RFC 9110, 15.5.19 (Unused) // StatusMisdirectedRequest indicates that the request was directed to a server that cannot respond appropriately. StatusMisdirectedRequest = 421 // RFC 9110, 15.5.20 // StatusUnprocessableEntity indicates that the request was well-formed but contains semantic errors. StatusUnprocessableEntity = 422 // RFC 9110, 15.5.21 // StatusLocked indicates that the requested resource is currently locked. StatusLocked = 423 // RFC 4918, 11.3 // StatusFailedDependency indicates that the request failed due to a failed dependency. StatusFailedDependency = 424 // RFC 4918, 11.4 // StatusTooEarly indicates that the request was sent too early and should be retried later. StatusTooEarly = 425 // RFC 8470, 5.2. // StatusUpgradeRequired indicates that the client should switch to a different protocol (e.g., HTTPS). StatusUpgradeRequired = 426 // RFC 9110, 15.5.22 // StatusPreconditionRequired indicates that a precondition header is required for the request. StatusPreconditionRequired = 428 // RFC 6585, 3 // StatusTooManyRequests indicates that the client has sent too many requests in a given period. StatusTooManyRequests = 429 // RFC 6585, 4 // StatusRequestHeaderFieldsTooLarge indicates that the request headers are too large for the server to process. StatusRequestHeaderFieldsTooLarge = 431 // RFC 6585, 5 StatusUnavailableForLegalReasons = 451 // RFC 7725, 3 // StatusInternalServerError indicates that the server encountered an unexpected condition. StatusInternalServerError = 500 // RFC 9110, 15.6.1 // StatusNotImplemented indicates that the server does not support the requested functionality. StatusNotImplemented = 501 // RFC 9110, 15.6.2 // StatusBadGateway indicates that the server, acting as a gateway or proxy, received an invalid response. StatusBadGateway = 502 // RFC 9110, 15.6.3 StatusServiceUnavailable = 503 // RFC 9110, 15.6.4 // StatusGatewayTimeout indicates that the server, acting as a gateway or proxy, did not receive a timely response. StatusGatewayTimeout = 504 // RFC 9110, 15.6.5 // StatusHTTPVersionNotSupported indicates that the server does not support the HTTP version used in the request. StatusHTTPVersionNotSupported = 505 // RFC 9110, 15.6.6 // StatusVariantAlsoNegotiates indicates that the server has an internal configuration error preventing negotiation. StatusVariantAlsoNegotiates = 506 // RFC 2295, 8.1 // StatusInsufficientStorage indicates that the server cannot store the representation needed to complete the request. StatusInsufficientStorage = 507 // RFC 4918, 11.5 // StatusLoopDetected indicates that the server detected an infinite loop while processing the request. StatusLoopDetected = 508 // RFC 5842, 7.2 // StatusNotExtended indicates that further extensions to the request are required for the server to fulfill it. StatusNotExtended = 510 // RFC 2774, 7 // StatusNetworkAuthenticationRequired indicates that the client must authenticate to gain network access. StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6 )
HTTP status codes as registered with IANA. See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const ( ContentTypeAppJSON = `application/json` ContentTypeAppXML = `application/xml` ContentTypeTextXML = `text/xml` )
Content-Type constants used for response headers
const ( Reset = "\033[0m" Blue = "\033[34m" Green = "\033[32m" Yellow = "\033[33m" Cyan = "\033[36m" Bold = "\033[1m" )
ANSI terminal color codes used for banner styling
const ACCUMULATED_CONTEXT_KEY = "__quick_context_data__"
const QuickVersion = "v0.0.1"
QuickVersion represents the current version of the Quick framework.
const SO_REUSEPORT = 0x0F
SO_REUSEPORT is a constant manually defined for Linux systems
Variables ΒΆ
var ContextDataCallback func(*http.Request, map[string]any)
ContextDataCallback is called when SetContext is invoked
Functions ΒΆ
func MaxBytesReader ΒΆ
func MaxBytesReader(w http.ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser
MaxBytesReader is a thin wrapper around http.MaxBytesReader to limit the size of the request body in Quick applications.
It returns an io.ReadCloser that reads from r but stops with an error after n bytes. The sink just sees an io.EOF.
This is useful to protect against large request bodies.
Example usage:
c.Request.Body = quick.MaxBytesReader(c.Response, c.Request.Body, 10_000) // 10KB
Example ΒΆ
This function is named ExampleMaxBytesReader()
it with the Examples type.
// Start Quick framework instance q := New() // Set max request body size to 1KB (1024 bytes) const maxBodySize = 1024 // Simulate a request using Quick's test utility with a payload exceeding 1KB oversizedBody := make([]byte, 2048) // 2KB of data to exceed the limit for i := range oversizedBody { oversizedBody[i] = 'A' } // Define a route with MaxBytesReader for extra validation q.Post("/v1/user/maxbody/max", func(c *Ctx) error { c.Set("Content-Type", "application/json") // Apply MaxBytesReader for additional size enforcement c.Request.Body = MaxBytesReader(c.Response, c.Request.Body, maxBodySize) // Read request body body, err := io.ReadAll(c.Request.Body) if err != nil { return c.Status(http.StatusRequestEntityTooLarge).String("Request body too large") } return c.Status(http.StatusOK).Send(body) }) // Simulate a request using Quick's test utility res, _ := q.Qtest(QuickTestOptions{ Method: MethodPost, URI: "/v1/user/maxbody/max", Headers: map[string]string{"Content-Type": "application/json"}, Body: oversizedBody, // Convert string to []byte }) if err := res.AssertStatus(413); err != nil { fmt.Println("status error:", err) } if err := res.AssertString("Request body too large"); err != nil { fmt.Println("body error:", err) } // Print response status and body for verification fmt.Println(res.StatusCode()) // Expecting: 413 (Payload too large) fmt.Println(res.BodyStr()) // Expecting: "Request body too large"
Output: 413 Request body too large
func NotFound ΒΆ
func NotFound(w http.ResponseWriter, r *http.Request)
NotFound sends a 404 Not Found response with optional custom body. It wraps http.NotFound and provides a Quick-style naming.
func SaveAll ΒΆ
func SaveAll(files []*UploadedFile, destination string) error
SaveAll saves all uploaded files to the specified directory.
This function iterates through a slice of uploaded files and saves them using the `Save()` method.
Parameters:
- files ([]*UploadedFile): Slice of uploaded files.
- destination (string): The directory where the files should be saved.
Returns:
- error: An error if any file fails to save.
Example Usage:
files := []*UploadedFile{file1, file2} err := SaveAll(files, "./uploads") if err != nil { log.Fatal("Failed to save all files:", err) }
Example ΒΆ
This function is named ExampleSaveAll() it with the Examples type.
q := New() // Define a POST route for uploading multiple files q.Post("/upload", func(c *Ctx) error { // Set file upload size limit c.FormFileLimit("10MB") // Retrieve multiple uploaded files files, err := c.FormFiles("file") if err != nil { return c.Status(400).JSON(Msg{ Msg: "Upload error", Error: err.Error(), }) } // Save all files to a directory (e.g., "uploads") err = SaveAll(files, "uploads") if err != nil { return c.Status(500).JSON(Msg{ Msg: "Failed to save files", Error: err.Error(), }) } // Return JSON response indicating success return c.Status(200).JSON(map[string]string{ "message": "All files saved successfully", }) }) // Create a list of UploadedFile instances to simulate multiple uploads files := []*UploadedFile{ { Info: FileInfo{ Filename: "file1.txt", Bytes: []byte("File 1 content"), }, }, { Info: FileInfo{ Filename: "file2.txt", Bytes: []byte("File 2 content"), }, }, } // Define the target directory for saving the files targetDir := "test_uploads" // Save all files using SaveAll function err := SaveAll(files, targetDir) // Handle result if err != nil { fmt.Println("Error saving files:", err) } else { fmt.Println("All files saved successfully!") }
Output: All files saved successfully!
func StatusText ΒΆ
StatusText returns a text for the HTTP status code. It returns the empty string if the code is unknown.
Example ΒΆ
This function is named ExampleStatusText() it with the Examples type.
fmt.Println(StatusText(200)) fmt.Println(StatusText(404)) fmt.Println(StatusText(500))
Output: OK Not Found Internal Server Error
Types ΒΆ
type Config ΒΆ
type Config struct { BodyLimit int64 // Deprecated: Use MaxBodySize instead MaxBodySize int64 // Maximum request body size allowed. MaxHeaderBytes int // Maximum number of bytes allowed in the HTTP headers. GOMAXPROCS int // defines the maximum number of CPU cores GCHeapThreshold int64 // GCHeapThreshold sets the memory threshold (in bytes) BufferPoolSize int // BufferPoolSize determines the size (in bytes) RouteCapacity int // Initial capacity of the route slice. MoreRequests int // Value to set GCPercent. influences the garbage collector performance. 0-1000 ReadTimeout time.Duration // Maximum duration for reading the entire request. WriteTimeout time.Duration // Maximum duration before timing out writes of the response. IdleTimeout time.Duration // Maximum amount of time to wait for the next request when keep-alives are enabled. ReadHeaderTimeout time.Duration // Amount of time allowed to read request headers. GCPercent int // Renamed to be more descriptive (0-1000) - influences the garbage collector performance. TLSConfig *tls.Config // Integrated TLS configuration CorsConfig *CorsConfig // Specific type for CORS Views template.TemplateEngine NoBanner bool // Flag to disable the Quick startup Display. }
Config defines various configuration options for the Quick server
func GetDefaultConfig ΒΆ
func GetDefaultConfig() Config
GetDefaultConfig returns the default configuration pre-defined for the system.
This function provides a standardized configuration setup, ensuring that new instances use a consistent and optimized set of defaults.
Returns:
- Config: A struct containing the default system configuration.
Example Usage:
// This function is typically used when initializing a new Quick instance // to ensure it starts with the default settings if no custom config is provided.
Example ΒΆ
This function is named ExampleGetDefaultConfig() it with the Examples type.
// Get the default configuration settings result := GetDefaultConfig() // Print individual configuration values fmt.Printf("BodyLimit: %d\n", result.BodyLimit) // Maximum request body size fmt.Printf("MaxBodySize: %d\n", result.MaxBodySize) // Maximum allowed body size for requests fmt.Printf("MaxHeaderBytes: %d\n", result.MaxHeaderBytes) // Maximum size for request headers fmt.Printf("RouteCapacity: %d\n", result.RouteCapacity) // Maximum number of registered routes fmt.Printf("MoreRequests: %d\n", result.MoreRequests) // Maximum concurrent requests allowed
Output: BodyLimit: 2097152 MaxBodySize: 2097152 MaxHeaderBytes: 1048576 RouteCapacity: 1000 MoreRequests: 290
type ContextBuilder ΒΆ
type ContextBuilder struct {
// contains filtered or unexported fields
}
func (*ContextBuilder) Bool ΒΆ
func (cb *ContextBuilder) Bool(key string, value bool) *ContextBuilder
Bool adds a boolean value to the context as a string and returns the builder for chaining.
Parameters:
- key: Context key name
- value: Boolean value to store (converted to "true" or "false")
Usage:
c.SetContext().Bool("authenticated", true).Bool("admin", false)
func (*ContextBuilder) Int ΒΆ
func (cb *ContextBuilder) Int(key string, value int) *ContextBuilder
Int adds an integer value to the context as a string and returns the builder for chaining.
Parameters:
- key: Context key name
- value: Integer value to store (converted to string)
Usage:
c.SetContext().Int("userID", 12345).Int("attempts", 3)
func (*ContextBuilder) Str ΒΆ
func (cb *ContextBuilder) Str(key, value string) *ContextBuilder
Str adds a string value to the context and returns the builder for chaining.
Parameters:
- key: Context key name
- value: String value to store
Usage:
c.SetContext().Str("service", "user-service").Str("function", "createUser")
type CorsConfig ΒΆ
type CorsConfig struct { Enabled bool // If true, enables CORS support Options map[string]string // Custom CORS options AllowAll bool // If true, allows all origins }
CorsConfig defines the CORS settings for Quick
type Ctx ΒΆ
type Ctx struct { Response http.ResponseWriter // HTTP response writer to send responses Request *http.Request // Incoming HTTP request object MoreRequests int // Counter for batch processing requests JsonStr string // Request body as a string (for JSON handling) Headers map[string][]string // Map of request headers Params map[string]string // Map of URL parameters Query map[string]string // Map of query parameters App *Quick // Reference to the Quick application instance Context context.Context // custom context // contains filtered or unexported fields }
Ctx represents the context of an HTTP request and response.
func (*Ctx) Accepts ΒΆ
Accepts sets the "Accept" header in the HTTP response.
This function assigns a specific accept type to the HTTP response header "Accept."
Parameters:
- acceptType: The MIME type to set in the "Accept" header.
Returns:
- *Ctx: The current context instance for method chaining.
Example ΒΆ
This function is named ExampleCtx_Accepts() it with the Examples type.
q := New() q.Get("/accepts", func(c *Ctx) error { // Set Accept header c.Accepts("application/json") return c.String("Accept Set") }) // Simulate a GET request res, _ := q.Qtest(QuickTestOptions{ Method: MethodGet, URI: "/accepts", }) if err := res.AssertString("Accept Set"); err != nil { fmt.Println("Body error:", err) } fmt.Println(res.Response().Header.Get("Accept")) fmt.Println(res.BodyStr())
Output: application/json Accept Set
func (*Ctx) Add ΒΆ
Add defines an HTTP header in the response.
This function sets the specified HTTP response header to the provided value.
Parameters:
- key: The name of the HTTP header to set.
- value: The value to assign to the header.
func (*Ctx) Append ΒΆ
Append adds a value to an HTTP response header.
This function appends a new value to an existing HTTP response header.
Parameters:
- key: The name of the HTTP header.
- value: The value to append to the header.
Example ΒΆ
This function is named ExampleCtx_Append() it with the Examples type.
q := New() q.Get("/append-header", func(c *Ctx) error { // Append multiple values to a custom header c.Append("X-Custom-Header", "Quick") return c.String("Header Appended") }) // Simulate a GET request and retrieve XML response res, _ := q.Qtest(QuickTestOptions{ Method: MethodGet, URI: "/append-header", }) if err := res.AssertString("Header Appended"); err != nil { fmt.Println("Body error:", err) } fmt.Println(res.Response().Header.Get("X-Custom-Header")) fmt.Println(res.BodyStr())
Output: Quick Header Appended
func (*Ctx) Bind ΒΆ
Bind parses and binds the request body to a Go struct.
This function extracts and maps the request body content to the given struct (v). It supports various content types and ensures proper deserialization.
Parameters:
- v: A pointer to the structure where the request body will be bound.
Returns:
- error: An error if parsing fails or if the structure is incompatible with the request body.
Example ΒΆ
This function is named ExampleCtx_Bind() it with the Examples type.
q := New() q.Post("/bind", func(c *Ctx) error { // Define a struct to map the JSON request body var data struct { Name string `json:"name"` Age int `json:"age"` } // Parse JSON body into struct err := c.Bind(&data) if err != nil { fmt.Println("Error in Bind:", err) return err } // Print extracted data in desired format fmt.Printf("%s %d\n", data.Name, data.Age) return nil }) // Simulate a POST request with JSON data res, _ := q.Qtest(QuickTestOptions{ Method: MethodPost, URI: "/bind", Headers: map[string]string{ "Content-Type": "application/json", }, Body: []byte(`{"name": "Quick", "age": 30}`), }) fmt.Println(res.BodyStr())
Output: Quick 30
func (*Ctx) Body ΒΆ
Body retrieves the request body as a byte slice.
This function returns the raw request body as a slice of bytes ([]byte).
Returns:
- []byte: The request body in its raw byte form.
Example ΒΆ
This function is named ExampleCtx_Body() it with the Examples type.
q := New() // Create a new context with a simulated request body q.Post("/body", func(c *Ctx) error { // Access the raw body body := c.Body() fmt.Println(string(body)) return c.Status(200).String("OK") }) res, _ := q.Qtest(QuickTestOptions{ Method: MethodPost, URI: "/body", Headers: map[string]string{ "Content-Type": "application/json", }, Body: []byte(`{"name": "Quick", "age": 28}`), }) if err := res.AssertStatus(200); err != nil { fmt.Println("Status error:", err) }
Output: {"name": "Quick", "age": 28}
func (*Ctx) BodyParser ΒΆ
BodyParser efficiently unmarshals the request body into the provided struct (v) based on the Content-Type header.
Supported content-types: - application/json - application/xml, text/xml
Parameters:
- v: The target structure to decode the request body into.
Returns:
- error: An error if decoding fails or if the content-type is unsupported.
Example ΒΆ
This function is named ExampleCtx_BodyParser() it with the Examples type.
q := New() q.Post("/parse", func(c *Ctx) error { // Define a struct for JSON parsing var data struct { Name string `json:"name"` Age int `json:"age"` } // Parse request body into the struct err := c.BodyParser(&data) if err != nil { fmt.Println("Erro ao analisar o corpo:", err) return err } // Print parsed data fmt.Printf("%s %d\n", data.Name, data.Age) return nil }) // Simulate a POST request with JSON data res, _ := q.Qtest(QuickTestOptions{ Method: MethodPost, URI: "/parse", Headers: map[string]string{ "Content-Type": "application/json", }, Body: []byte(`{"name": "Quick", "age": 28}`), }) fmt.Println(res.BodyStr())
Output: Quick 28
func (*Ctx) BodyString ΒΆ
BodyString retrieves the request body as a string.
This function converts the request body from a byte slice into a string format.
Returns:
- string: The request body as a string.
Example ΒΆ
This function is named ExampleCtx_Body() it with the Examples type.
q := New() q.Post("/bodyString", func(c *Ctx) error { // Access the raw body bodyStr := c.BodyString() fmt.Println(bodyStr) return c.Status(200).String("OK") }) res, _ := q.Qtest(QuickTestOptions{ Method: MethodPost, URI: "/bodyString", Headers: map[string]string{ "Content-Type": "application/json", }, Body: []byte(`{"name": "Quick", "age": 28}`), }) if err := res.AssertStatus(200); err != nil { fmt.Println("Status error:", err) }
Output: {"name": "Quick", "age": 28}
func (*Ctx) Byte ΒΆ
Byte writes a byte slice to the HTTP response.
This function writes raw bytes to the response body using writeResponse().
Parameters:
- b: The byte slice to be written.
Returns:
- error: An error if the response write operation fails.
Example ΒΆ
This function is named ExampleCtx_Byte() it with the Examples type.
q := New() q.Get("/byte", func(c *Ctx) error { // Send raw byte array in response return c.Byte([]byte("Hello, Quick!")) }) // Simulate a GET request res, _ := q.Qtest(QuickTestOptions{ Method: MethodGet, URI: "/byte", }) if err := res.AssertString("Hello, Quick!"); err != nil { fmt.Println("Body error:", err) } fmt.Println(res.BodyStr())
Output: Hello, Quick!
func (*Ctx) Ctx ΒΆ
Ctx returns the active context for this request. It returns the custom context if SetCtx was used; otherwise defaults to Request.Context()
func (*Ctx) File ΒΆ
File serves a specific file to the client.
This function trims any trailing "/*" from the provided file path, checks if it is a directory, and serves "index.html" if applicable. If the file exists, it is sent as the response.
Parameters:
- filePath: The path to the file to be served.
Returns:
- error: Always returns nil, as `http.ServeFile` handles errors internally.
Example ΒΆ
This function is named ExampleCtx_File() it with the Examples type.
// Creating a Quick instance q := New() // Defining a route that serves a specific file q.Get("/file", func(c *Ctx) error { return c.File("./test_uploads/quick.txt") // Serves an existing file }) // Simulating a request to test the route // Simulate a GET request res, _ := q.Qtest(QuickTestOptions{ Method: MethodGet, URI: "/file", }) if err := res.AssertStatus(200); err != nil { fmt.Println("Status error:", err) } fmt.Println("Status:", res.StatusCode())
Output: Status: 200
func (*Ctx) FormFile ΒΆ
func (c *Ctx) FormFile(fieldName string) (*UploadedFile, error)
FormFile processes an uploaded file and returns its details.
This function retrieves the first uploaded file for the specified form field.
Parameters:
- fieldName: The name of the form field containing the uploaded file.
Returns:
- *UploadedFile: A struct containing the uploaded file details.
- error: An error if no file is found or the retrieval fails.
Example ΒΆ
This function is named ExampleCtx_FormFile() it with the Examples type.
// Simulated uploaded file uploadedFile := &UploadedFile{ Info: FileInfo{ Filename: "quick.txt", Size: 1024, ContentType: "text/plain", Bytes: []byte("File content"), }, } // Mocking the FormFiles function externally mockFormFiles := func(fieldName string) ([]*UploadedFile, error) { if fieldName == "file" { return []*UploadedFile{uploadedFile}, nil } return nil, errors.New("file not found") } // Calling the mocked function instead of modifying `ctx` files, err := mockFormFiles("file") // Handling the result if err != nil { fmt.Println("Error:", err) } else if len(files) > 0 { fmt.Println("Received file:", files[0].FileName()) }
Output: Received file: quick.txt
func (*Ctx) FormFileLimit ΒΆ
FormFileLimit sets the maximum allowed upload size.
This function configures the maximum file upload size for multipart form-data requests.
Parameters:
- limit: A string representing the maximum file size (e.g., "10MB").
Returns:
- error: An error if the limit value is invalid.
Example ΒΆ
This function is named ExampleCtx_FormFileLimit() it with the Examples type.
// Creating a new context ctx := &Ctx{} // Setting a file upload limit to 5MB err := ctx.FormFileLimit("5MB") // Checking if an error occurred while setting the limit if err != nil { fmt.Println("Error:", err) } else { fmt.Println("Upload limit set to:", ctx.uploadFileSize) }
Output: Upload limit set to: 5242880
func (*Ctx) FormFiles ΒΆ
func (c *Ctx) FormFiles(fieldName string) ([]*UploadedFile, error)
FormFiles retrieves all uploaded files for the given field name.
This function extracts all files uploaded in a multipart form request.
Parameters:
- fieldName: The name of the form field containing the uploaded files.
Returns:
- []*UploadedFile: A slice containing details of the uploaded files.
- error: An error if no files are found or the retrieval fails.
Example ΒΆ
This function is named ExampleCtx_FormFiles() it with the Examples type.
// Simulating multiple uploaded files uploadedFiles := []*UploadedFile{ { Info: FileInfo{ Filename: "file1.txt", Size: 1024, ContentType: "text/plain", Bytes: []byte("File 1 content"), }, }, { Info: FileInfo{ Filename: "file2.txt", Size: 2048, ContentType: "text/plain", Bytes: []byte("File 2 content"), }, }, } // Mocking the FormFiles function externally mockFormFiles := func(fieldName string) ([]*UploadedFile, error) { if fieldName == "files" { return uploadedFiles, nil } return nil, errors.New("files not found") } // Calling the mocked function instead of modifying `ctx` files, err := mockFormFiles("files") // Handling the result if err != nil { fmt.Println("Error:", err) } else { fmt.Println("Received files:") for _, file := range files { fmt.Printf("- %s (%d bytes)\n", file.FileName(), file.Size()) } }
Output: Received files: - file1.txt (1024 bytes) - file2.txt (2048 bytes)
func (*Ctx) FormValue ΒΆ
FormValue retrieves a form value by its key.
This function parses the form data and returns the value of the specified field.
Parameters:
- key: The name of the form field.
Returns:
- string: The value of the requested field, or an empty string if not found.
func (*Ctx) FormValues ΒΆ
FormValues retrieves all form values as a map.
This function parses the form data and returns all form values.
Returns:
- map[string][]string: A map of form field names to their corresponding values.
func (*Ctx) Get ΒΆ
Get retrieves a specific header value from the request.
Parameters:
- key: The name of the header to retrieve.
Returns:
- string: The value of the specified header, or an empty string if not found.
func (*Ctx) GetAllContextData ΒΆ
GetAllContextData returns all accumulated context data.
Usage:
allData := c.GetAllContextData() fmt.Printf("Context: %+v", allData)
func (*Ctx) GetHeader ΒΆ
GetHeader retrieves a specific header value from the request.
Parameters:
- key: The name of the header to retrieve.
Returns:
- string: The value of the specified header, or an empty string if not found.
Example ΒΆ
This function is named ExampleCtx_GetHeader() it with the Examples type.
q := New() // Defining a route that serves a specific file q.Get("/header", func(c *Ctx) error { // Retrieve the "User-Agent" header header := c.GetHeader("User-Agent") c.Set("User-Agent", header) fmt.Println(header) return nil }) // Simulate a GET request res, _ := q.Qtest(QuickTestOptions{ Method: MethodGet, URI: "/header", Headers: map[string]string{"User-Agent": "Go-Test-Agent"}, }) if err := res.AssertStatus(200); err != nil { fmt.Println("Status error:", err) } if err := res.AssertHeader("User-Agent", "Go-Test-Agent"); err != nil { fmt.Println("Header error:", err) } fmt.Println("Status:", res.StatusCode())
Output: Go-Test-Agent Status: 200
func (*Ctx) GetHeaders ΒΆ
GetHeaders retrieves all headers from the incoming HTTP request.
This method provides direct access to the request headers, allowing middleware and handlers to inspect and modify header values.
Example Usage:
q.Get("/", func(c *quick.Ctx) error { headers := c.GetHeaders() return c.Status(200).JSON(headers) })
Returns:
- http.Header: A map containing all request headers.
Example ΒΆ
This function is named ExampleCtx_GetHeaders() it with the Examples type.
q := New() q.Get("/headers", func(c *Ctx) error { // Retrieve all request headers headers := c.GetHeaders() c.Set("Content-Type", headers.Get("Content-Type")) c.Set("Accept", headers.Get("Accept")) // Print specific headers for demonstration fmt.Println(headers.Get("Content-Type")) // Expected output: "application/json" fmt.Println(headers.Get("Accept")) // Expected output: "application/xml" return nil }) res, _ := q.Qtest(QuickTestOptions{ Method: MethodGet, URI: "/headers", Headers: map[string]string{ "Content-Type": "application/json", "Accept": "application/xml", }, }) if err := res.AssertHeader("Content-Type", "application/json"); err != nil { fmt.Println("Header error:", err) } if err := res.AssertHeader("Accept", "application/xml"); err != nil { fmt.Println("Header error:", err) } fmt.Println("Status:", res.StatusCode())
Output: application/json application/xml Status: 200
func (*Ctx) GetHeadersAll ΒΆ
GetHeadersAll returns all HTTP response headers stored in the context.
Returns:
- map[string][]string: A map containing all response headers with their values.
Example ΒΆ
This function is named ExampleCtx_GetHeadersAll() it with the Examples type.
q := New() q.Get("/headers", func(c *Ctx) error { // Retrieve all headers from the request headers := c.GetHeadersAll() fmt.Println(headers["Content-Type"]) // Expected: application/json fmt.Println(headers["Accept"]) // Expected: application/xml return nil }) // Simulate a GET request with headers res, _ := q.Qtest(QuickTestOptions{ Method: MethodGet, URI: "/headers", Headers: map[string]string{ "Content-Type": "application/json", "Accept": "application/xml"}, }) if err := res.AssertStatus(200); err != nil { fmt.Println("Status error:", err) }
Output: [application/json] [application/xml]
func (*Ctx) GetReqHeadersAll ΒΆ
QueryParam retrieves a query parameter value from the URL.
Parameters:
- key: The name of the query parameter to retrieve.
Returns:
- string: The value of the specified query parameter, or an empty string if not found.
Example ΒΆ
This function is named ExampleCtx_GetReqHeadersAll() it with the Examples type.
q := New() q.Get("/headers", func(c *Ctx) error { // Retrieve all request headers headers := c.GetReqHeadersAll() // Print specific headers for demonstration fmt.Println(headers["Content-Type"]) // Expected: application/json fmt.Println(headers["Accept"]) // Expected: application/xml return nil }) // Simulate a GET request with headers res, _ := q.Qtest(QuickTestOptions{ Method: MethodGet, URI: "/headers", Headers: map[string]string{ "Content-Type": "application/json", "Accept": "application/xml"}, }) if err := res.AssertStatus(200); err != nil { fmt.Println("Status error:", err) } fmt.Println("Status:", res.StatusCode())
Output: [application/json] [application/xml] Status: 200
func (*Ctx) GetTraceID ΒΆ
GetTraceID retrieves or generates a trace ID for the current request.
This method first attempts to get an existing trace ID from the request headers. If no trace ID is found, it automatically generates a new one using a random trace ID generator. This ensures that every request has a unique trace ID for distributed tracing purposes.
Parameters:
- nameTraceID: The header name to look for the trace ID (e.g., "X-Trace-ID", "Trace-ID")
Returns:
- traceID: The existing trace ID from headers, or a newly generated one if none exists
This method is typically used at the beginning of request processing to ensure traceability across your application stack. The generated trace ID can then be used with SetTraceContext or forwarded to downstream services.
Usage:
func myHandler(c *quick.Ctx) error { traceID := c.GetTraceID("X-Trace-ID") c.SetTraceContext("X-Trace-ID", traceID, "user-service", "createUser") // Continue with your handler logic return c.Status(200).String(traceID) }
func (*Ctx) Host ΒΆ
Host returns the host name from the HTTP request.
This method extracts the host from `c.Request.Host`. If the request includes a port number (e.g., "localhost:3000"), it returns the full host including the port.
Example Usage:
q.Get("/", func(c *quick.Ctx) error { return c.Status(200).SendString("Host: " + c.Host()) })
Returns:
- string: The host name from the request.
func (*Ctx) JSON ΒΆ
JSON encodes the provided interface (v) as JSON, sets the Content-Type header, and writes the response efficiently using buffer pooling.
Parameters:
- v: The data structure to encode as JSON.
Returns:
- error: An error if JSON encoding fails or if writing the response fails.
Example ΒΆ
This function is named ExampleCtx_JSON() it with the Examples type.
q := New() q.Get("/json", func(c *Ctx) error { // Define JSON response data data := map[string]string{"message": "Hello, Quick!"} return c.JSON(data) }) // Simulate a GET request and retrieve JSON response res, _ := q.Qtest(QuickTestOptions{ Method: MethodGet, URI: "/json", Headers: map[string]string{ "Content-Type": "application/json", }, }) if err := res.AssertString("{\"message\":\"Hello, Quick!\"}"); err != nil { fmt.Println("Body error:", err) } fmt.Println(res.BodyStr())
Output: {"message":"Hello, Quick!"}
func (*Ctx) JSONIN ΒΆ
JSONIN encodes the given interface as JSON with indentation and writes it to the HTTP response. Allows optional parameters to define the indentation format.
ATTENTION use only for debugging, very slow
Parameters:
- v: The data structure to encode as JSON.
- params (optional): Defines the indentation settings.
- If params[0] is provided, it will be used as the prefix.
- If params[1] is provided, it will be used as the indentation string.
Returns:
- error: An error if JSON encoding fails or if writing to the ResponseWriter fails.
Example ΒΆ
This function is named ExampleCtx_JSONIN() it with the Examples type.
// Creating a Quick instance q := New() // Defining a route that serves a specific file q.Get("/json", func(c *Ctx) error { data := map[string]string{"message": "Hello, Quick!"} return c.JSONIN(data) }) // Simulate a GET request res, _ := q.Qtest(QuickTestOptions{ Method: MethodGet, URI: "/json", }) if err := res.AssertStatus(200); err != nil { fmt.Println("Status error:", err) } if err := res.AssertString("{\n \"message\": \"Hello, Quick!\"\n}\n"); err != nil { fmt.Println("Body error:", err) } fmt.Println("Status:", res.StatusCode()) fmt.Println("Body:", res.BodyStr())
Output: Status: 200 Body: { "message": "Hello, Quick!" }
func (*Ctx) Logger ΒΆ
func (c *Ctx) Logger() *ContextBuilder
Logger creates a new context builder for adding key-value pairs.
Usage:
c.Logger().Str("service", "user-service").Int("userID", 123)
func (*Ctx) Method ΒΆ
Method retrieves the HTTP method of the current request.
This method returns the HTTP method as a string, such as "GET", "POST", "PUT", "DELETE", etc. It is useful for middleware and route handlers to differentiate between request types.
Example Usage:
q.Use(func(c *quick.Ctx) error { if c.Method() == "POST" { return c.Status(403).SendString("POST requests are not allowed") } return c.Next() })
Returns:
- string: The HTTP method (e.g., "GET", "POST", "PUT").
Example ΒΆ
This function is named ExampleCtx_Method() it with the Examples type.
q := New() q.Post("/method", func(c *Ctx) error { fmt.Println(c.Method()) // Expected output: "POST" return nil }) // Simulate a POST request res, _ := q.Qtest(QuickTestOptions{ Method: MethodPost, URI: "/method", }) if err := res.AssertStatus(200); err != nil { fmt.Println("Status error:", err) } fmt.Println(res.BodyStr())
Output: POST
func (*Ctx) MultipartForm ΒΆ
MultipartForm provides access to the raw multipart form data.
This function parses and retrieves the multipart form from the request.
Returns:
- *multipart.Form: A pointer to the multipart form data.
- error: An error if parsing fails.
Example ΒΆ
This function is named ExampleCtx_MultipartForm() it with the Examples type.
// Create a multipart/form-data body using a buffer var body bytes.Buffer writer := multipart.NewWriter(&body) // Add a sample form field "username" with value "quickuser" _ = writer.WriteField("username", "quickuser") // Close the writer to finalize the form body (writes the boundary end) writer.Close() // Create a new Quick context manually ctx := &Ctx{} // Construct a fake HTTP request with method POST and the correct headers ctx.Request = &http.Request{ Method: "POST", Header: http.Header{ // Set the Content-Type to multipart/form-data with the proper boundary "Content-Type": []string{writer.FormDataContentType()}, }, Body: http.NoBody, // Temporary placeholder, will be replaced below ContentLength: int64(body.Len()), } // Set the actual body (must be an io.ReadCloser) ctx.Request.Body = io.NopCloser(&body) // Attempt to parse the multipart form from the request form, err := ctx.MultipartForm() // Print the result if err != nil { fmt.Println("Error processing form:", err) } else { fmt.Println("Form processed successfully:", form.Value) }
Output: Form processed successfully: map[username:[quickuser]]
func (*Ctx) Next ΒΆ
Next executes the next handler in the chain.
If no more handlers are available and no response has been written, it automatically sends a 404 response.
Usage:
func myMiddleware(c *quick.Ctx) error { err := c.Next() return err }
Example ΒΆ
This function is named ExampleCtx_Next() it with the Examples type.
q := New() // Middleware that uses Next q.Use(func(c *Ctx) error { err := c.Next() return err }) // Final route handler q.Get("/", func(c *Ctx) error { fmt.Println("Quick") return c.String("done") }) // Simulate request res, _ := q.Qtest(QuickTestOptions{ Method: MethodGet, URI: "/", }) // Ensure response is what we expect if err := res.AssertString("done"); err != nil { fmt.Println("Body error:", err) } if err := res.AssertStatus(200); err != nil { fmt.Println("Status error:", err) }
Output: Quick
func (*Ctx) OriginalURI ΒΆ
OriginalURI retrieves the original request URI sent by the client.
This method returns the full unprocessed request URI, including the path and optional query string, exactly as it was sent by the client. It can be useful for logging, debugging, or routing decisions that depend on the raw URI.
Example Usage:
q.Use(func(c *quick.Ctx) error { uri := c.OriginalURI() if strings.HasPrefix(uri, "/admin") { return c.Status(401).SendString("Unauthorized access to admin area") } return c.Next() })
Returns:
- string: The raw request URI (e.g., "/api/v1/resource?id=123").
func (*Ctx) Param ΒΆ
Param retrieves the value of a URL parameter corresponding to the given key.
This function searches for a parameter in the request's URL path and returns its value. If the parameter is not found, an empty string is returned.
Parameters:
- key: The name of the URL parameter to retrieve.
Returns:
- string: The value of the requested parameter or an empty string if not found.
Example ΒΆ
This function is named ExampleCtx_Param() it with the Examples type.
q := New() q.Get("/user/:id", func(c *Ctx) error { // Retrieve "id" parameter from the URL path id := c.Param("id") return c.SendString(id) }) // Simulate a GET request with a path parameter res, _ := q.Qtest(QuickTestOptions{ Method: MethodGet, URI: "/user/42", Headers: map[string]string{ "Content-Type": "application/json", }, }) if err := res.AssertStatus(200); err != nil { fmt.Println("Status error:", err) } fmt.Println(res.BodyStr())
Output: 42
func (*Ctx) Path ΒΆ
Path retrieves the URL path of the incoming HTTP request.
This method extracts the path component from the request URL, which is useful for routing and request handling.
Example Usage:
q.Get("/info", func(c *quick.Ctx) error { return c.Status(200).SendString("Requested Path: " + c.Path()) })
Returns:
- string: The path component of the request URL (e.g., "/v1/user").
Example ΒΆ
This function is named ExampleCtx_Path() it with the Examples type.
q := New() q.Get("/path/to/resource", func(c *Ctx) error { fmt.Println(c.Path()) // Expected output: "/path/to/resource" return nil }) // Simulate a GET request res, _ := q.Qtest(QuickTestOptions{ Method: MethodGet, URI: "/path/to/resource", }) if err := res.AssertStatus(200); err != nil { fmt.Println("Status error:", err) } fmt.Println(res.BodyStr())
Output: /path/to/resource
func (*Ctx) QueryParam ΒΆ
QueryParam retrieves a query parameter value from the URL.
Parameters:
- key: The name of the query parameter to retrieve.
Returns:
- string: The value of the specified query parameter, or an empty string if not found.
Example ΒΆ
This function is named ExampleCtx_QueryParam() it with the Examples type.
q := New() q.Get("/search", func(c *Ctx) error { fmt.Println(c.QueryParam("query")) // Expected output: "quick" return nil }) // Simulate a GET request with query parameters res, _ := q.Qtest(QuickTestOptions{ Method: MethodGet, URI: "/search?query=quick", QueryParams: map[string]string{"query": "quick"}, }) if err := res.AssertStatus(200); err != nil { fmt.Println("Status error:", err) } fmt.Println(res.BodyStr())
Output: quick
func (*Ctx) Redirect ΒΆ
Redirect sends an HTTP redirect response to the client.
It sets the "Location" header to the given URL and returns a plain text message indicating the redirection. By default, it uses HTTP status 302 (Found), but an optional custom status code can be provided (e.g., 301, 307, 308).
Example usage:
c.Redirect("https://quick.com") c.Redirect("/new-path", 301)
Example ΒΆ
This function is named ExampleCtx_Redirect() it with the Examples type.
q := New() q.Get("/old-path", func(c *Ctx) error { return c.Redirect("/new-path") }) // Simulate a GET request res, _ := q.Qtest(QuickTestOptions{ Method: MethodGet, URI: "/old-path", }) if err := res.AssertStatus(StatusFound); err != nil { fmt.Println("Status error:", err) } fmt.Println("Location header:", res.Response().Header.Get("Location")) fmt.Println("Status:", res.StatusCode()) fmt.Println("Body:", res.BodyStr())
Output: Location header: /new-path Status: 302 Body: Redirecting to /new-path
func (*Ctx) RemoteIP ΒΆ
RemoteIP extracts the client's IP address from the request.
If the request's `RemoteAddr` contains a port (e.g., "192.168.1.100:54321"), this method extracts only the IP part. If extraction fails, it returns the full `RemoteAddr` as a fallback.
Example Usage:
q.Get("/", func(c *quick.Ctx) error { return c.Status(200).SendString("Client IP: " + c.RemoteIP()) })
Returns:
- string: The client's IP address. If extraction fails, returns `RemoteAddr`.
Example ΒΆ
This function is named ExampleCtx_RemoteIP() it with the Examples type.
q := New() q.Get("/ip", func(c *Ctx) error { // Retrieve the client's IP address clientIP := c.RemoteIP() // Print the IP address for demonstration purposes fmt.Println(clientIP) return nil }) // Simulate a GET request setting a fixed IP in RemoteAddr req := httptest.NewRequest("GET", "/ip", nil) req.RemoteAddr = "192.168.1.100:54321" // Setting a fixed IP for testing rec := httptest.NewRecorder() // Serve the request q.ServeHTTP(rec, req) // Capture and print the response fmt.Println(strings.TrimSpace(rec.Body.String()))
Output: 192.168.1.100
func (*Ctx) Reset ΒΆ
func (c *Ctx) Reset(w http.ResponseWriter, r *http.Request)
Reset clears Ctx data for safe reuse
func (*Ctx) Send ΒΆ
Send writes a byte slice to the HTTP response.
This function writes raw bytes to the response body using writeResponse().
Parameters:
- b: The byte slice to be written.
Returns:
- error: An error if the response write operation fails.
Example ΒΆ
This function is named ExampleCtx_Send() it with the Examples type.
q := New() q.Get("/send", func(c *Ctx) error { // Send raw bytes in response return c.Send([]byte("Hello, Quick!")) }) // Simulate a GET request res, _ := q.Qtest(QuickTestOptions{ Method: MethodGet, URI: "/send", }) if err := res.AssertString("Hello, Quick!"); err != nil { fmt.Println("Body error:", err) } fmt.Println(res.BodyStr())
Output: Hello, Quick!
func (*Ctx) SendFile ΒΆ
SendFile writes a file to the HTTP response as a byte slice.
This function writes the provided byte slice (representing a file) to the response body.
Parameters:
- file: The file content as a byte slice.
Returns:
- error: An error if the response write operation fails.
Example ΒΆ
This function is named ExampleCtx_SendFile() it with the Examples type.
q := New() q.Get("/sendfile", func(c *Ctx) error { // Simulate sending a file as a response fileContent := []byte("file contents") return c.SendFile(fileContent) }) // Simulate a GET request res, _ := q.Qtest(QuickTestOptions{ Method: MethodGet, URI: "/sendfile", }) if err := res.AssertString("file contents"); err != nil { fmt.Println("Body error:", err) } fmt.Println(res.BodyStr())
Output: file contents
func (*Ctx) SendString ΒΆ
SendString writes a string to the HTTP response.
This function converts the given string into a byte slice and writes it to the response body.
Parameters:
- s: The string to be written.
Returns:
- error: An error if the response write operation fails.
Example ΒΆ
This function is named ExampleCtx_SendString() it with the Examples type.
q := New() q.Get("/sendstring", func(c *Ctx) error { // Send string response return c.SendString("Hello, Quick!") }) // Simulate a GET request res, _ := q.Qtest(QuickTestOptions{ Method: MethodGet, URI: "/sendstring", }) if err := res.AssertString("Hello, Quick!"); err != nil { fmt.Println("Body error:", err) } fmt.Println(res.BodyStr())
Output: Hello, Quick!
func (*Ctx) Set ΒΆ
Set defines an HTTP header in the response.
This function sets the specified HTTP response header to the provided value.
Parameters:
- key: The name of the HTTP header to set.
- value: The value to assign to the header.
Example ΒΆ
This function is named ExampleCtx_Set() it with the Examples type.
q := New() q.Get("/set-header", func(c *Ctx) error { // Set a custom response header c.Set("X-Custom-Header", "Quick") return c.String("Header Set") }) // Simulate a GET request res, _ := q.Qtest(QuickTestOptions{ Method: MethodGet, URI: "/set-header", }) if err := res.AssertString("Header Set"); err != nil { fmt.Println("Body error:", err) } fmt.Println(res.Response().Header.Get("X-Custom-Header")) fmt.Println(res.BodyStr())
Output: Quick Header Set
func (*Ctx) SetContext ΒΆ
func (c *Ctx) SetContext() *ContextBuilder
SetContext creates a new context builder for adding key-value pairs.
Usage:
c.SetContext().Str("service", "user-service").Int("userID", 123)
func (*Ctx) SetStatus ΒΆ
SetStatus sets the HTTP response status code.
Parameters:
- status: The HTTP status code to be set.
func (*Ctx) SetTraceID ΒΆ
func (c *Ctx) SetTraceID(key, val string) *ContextBuilder
SetTraceID sets a trace ID header and adds it to the context.
Parameters:
- key: Header name (e.g., "X-Trace-ID")
- val: Trace ID value
Returns a ContextBuilder for chaining additional context data.
Usage:
c.SetTraceID("X-Trace-ID", traceID).Str("service", "user-service")
func (*Ctx) Status ΒΆ
Status sets the HTTP status code of the response.
This function assigns a specific HTTP status code to the response.
Parameters:
- status: The HTTP status code to set.
Returns:
- *Ctx: The current context instance for method chaining.
Example ΒΆ
This function is named ExampleCtx_Status() it with the Examples type.
q := New() q.Get("/status", func(c *Ctx) error { // Set status code to 404 c.Status(404) return c.String("Not Found") }) // Simulate a GET request res, _ := q.Qtest(QuickTestOptions{ Method: MethodGet, URI: "/status", }) if err := res.AssertString("Not Found"); err != nil { fmt.Println("Body error:", err) } fmt.Println(res.Response().StatusCode)
Output: 404
func (*Ctx) String ΒΆ
String writes a string to the HTTP response.
This function converts the given string into a byte slice and writes it to the response body.
Parameters:
- s: The string to be written.
Returns:
- error: An error if the response write operation fails.
Example ΒΆ
This function is named ExampleCtx_String() it with the Examples type.
q := New() q.Get("/string", func(c *Ctx) error { // Return a simple string response return c.String("Hello, Quick!") }) // Simulate a GET request res, _ := q.Qtest(QuickTestOptions{ Method: MethodGet, URI: "/string", }) if err := res.AssertString("Hello, Quick!"); err != nil { fmt.Println("Body error:", err) } fmt.Println(res.BodyStr())
Output: Hello, Quick!
func (*Ctx) XML ΒΆ
XML serializes the given value to XML and writes it to the HTTP response. It avoids unnecessary memory allocations by using buffer pooling and ensures that no extra newline is appended.
Parameters:
- v: The data structure to encode as XML.
Returns:
- error: An error if XML encoding fails or if writing to the ResponseWriter fails.
Example ΒΆ
This function is named ExampleCtx_XML() it with the Examples type.
q := New() q.Get("/xml", func(c *Ctx) error { type XMLResponse struct { XMLName xml.Name `xml:"message"` Text string `xml:",chardata"` } data := XMLResponse{Text: "Hello, Quick!"} xmlBytes, err := xml.Marshal(data) if err != nil { return c.Status(500).String("Failed to marshal XML") } c.Set("Content-Type", "application/xml") return c.Status(200).Send(xmlBytes) }) // Simulate a GET request and retrieve XML response res, _ := q.Qtest(QuickTestOptions{ Method: MethodGet, URI: "/xml", Headers: map[string]string{ "Accept": "application/xml", }, }) if err := res.AssertString(`<message>Hello, Quick!</message>`); err != nil { fmt.Println("Body error:", err) } fmt.Println(res.BodyStr())
Output: <message>Hello, Quick!</message>
type Error ΒΆ
type Error struct { Message string `json:"message"` // Error message to be returned to the client. Code int `json:"code"` // HTTP status code associated with the error. }
Error represents a custom HTTP error that can be returned from a handler. It implements the error interface and is designed to work seamlessly with Quick's global error handler.
Example usage:
return quick.NewError(404, "Resource not found")
func NewError ΒΆ
NewError creates a new instance of Error with the specified HTTP status code. An optional custom message can be provided. If no message is provided, the default HTTP status text for the given code will be used.
Example usage:
err := quick.NewError(400, "Invalid input") err := quick.NewError(500) // Uses "Internal Server Error" as message
type FileInfo ΒΆ
FileInfo contains metadata about an uploaded file.
Fields:
- Filename: The original name of the uploaded file.
- Size: The file size in bytes.
- ContentType: The MIME type of the file (e.g., "image/png").
- Bytes: The raw file content as a byte slice.
type Group ΒΆ
type Group struct {
// contains filtered or unexported fields
}
Group represents a collection of routes that share a common prefix.
Fields:
- prefix: The URL prefix shared by all routes in the group.
- routes: A list of registered routes within the group.
- middlewares: A list of middleware functions applied to the group.
- quick: A reference to the Quick router.
func (*Group) Delete ΒΆ
func (g *Group) Delete(pattern string, handlerFunc HandleFunc)
Delete registers a new DELETE route.
Parameters:
- pattern: The route pattern.
- handlerFunc: The function handling the request.
Example:
g.Delete("/users/:id", deleteUserHandler)
Example ΒΆ
This function is named ExampleGroup_Delete() it with the Examples type.
q := New() // Create a route group with prefix "/api" apiGroup := q.Group("/api") // Define a DELETE route inside the group apiGroup.Delete("/users/:id", func(c *Ctx) error { // Return a success message return c.Status(200).String("User deleted") }) // Simulate a DELETE request to "/api/users/42" res, _ := q.Qtest(QuickTestOptions{ Method: MethodDelete, URI: "/api/users/42", }) if err := res.AssertStatus(200); err != nil { fmt.Println("Status error:", err) } if err := res.AssertString("User deleted"); err != nil { fmt.Println("Body error:", err) } // Print the response body fmt.Println(res.BodyStr())
Output: User deleted
func (*Group) Get ΒΆ
func (g *Group) Get(pattern string, handlerFunc HandleFunc)
Get registers a new GET route.
Parameters:
- pattern: The route pattern.
- handlerFunc: The function handling the request.
Example:
g.Get("/users", listUsersHandler)
Example ΒΆ
This function is named ExampleGroup_Get() it with the Examples type.
q := New() // Create a route group with prefix "/api" apiGroup := q.Group("/api") // Define a GET route inside the group apiGroup.Get("/users", func(c *Ctx) error { // Return a success message return c.Status(200).String("List of users") }) // Simulate a GET request to "/api/users" res, _ := q.Qtest(QuickTestOptions{ Method: MethodGet, URI: "/api/users", }) if err := res.AssertStatus(200); err != nil { fmt.Println("Status error:", err) } if err := res.AssertString("List of users"); err != nil { fmt.Println("Body error:", err) } fmt.Println(res.BodyStr())
Output: List of users
func (*Group) Handle ΒΆ
func (g *Group) Handle(method, pattern string, handlerFunc HandleFunc, paramExtractor any)
Handle registers a new route dynamically.
Parameters:
- method: The HTTP method (GET, POST, etc.).
- pattern: The route pattern.
- handlerFunc: The function handling the request.
- paramExtractor: The function to extract parameters.
Example:
g.Handle("GET", "/users/:id", userHandler, extractParamsGet)
func (*Group) Options ΒΆ
func (g *Group) Options(pattern string, handlerFunc HandleFunc)
Options registers a new OPTIONS route.
Parameters:
- pattern: The route pattern.
- handlerFunc: The function handling the request.
Example:
g.Options("/users", optionsHandler)
Example ΒΆ
This function is named ExampleGroup_Options() it with the Examples type.
// Create a new Quick instance q := New() // Create a new group with a common prefix api := q.Group("/api") // Register an OPTIONS route dynamically api.Options("/resource", func(c *Ctx) error { c.Set("Allow", "GET, POST, OPTIONS") return c.Status(204).Send(nil) // No Content response }) // Simulate an OPTIONS request res, _ := q.Qtest(QuickTestOptions{ Method: MethodOptions, URI: "/api/resource", }) if err := res.AssertStatus(204); err != nil { fmt.Println("Status error:", err) } // Print the response status fmt.Println("Status:", res.StatusCode())
Output: Status: 204
func (*Group) Patch ΒΆ
func (g *Group) Patch(pattern string, handlerFunc HandleFunc)
Patch registers a new PATCH route.
Parameters:
- pattern: The route pattern.
- handlerFunc: The function handling the request.
Example:
g.Patch("/users/:id", partialUpdateHandler)
Example ΒΆ
This function is named ExampleGroup_Patch() it with the Examples type.
// Create a new Quick instance q := New() // Create a new group with a common prefix api := q.Group("/api") // Register a PATCH route dynamically api.Patch("/update", func(c *Ctx) error { return c.Status(200).String("PATCH request received") }) // Simulate a PATCH request res, _ := q.Qtest(QuickTestOptions{ Method: MethodPatch, URI: "/api/update", }) if err := res.AssertStatus(200); err != nil { fmt.Println("Status error:", err) } if err := res.AssertString("PATCH request received"); err != nil { fmt.Println("Body error:", err) } // Print the response body fmt.Println(res.BodyStr())
Output: PATCH request received
func (*Group) Post ΒΆ
func (g *Group) Post(pattern string, handlerFunc HandleFunc)
Post registers a new POST route.
Parameters:
- pattern: The route pattern.
- handlerFunc: The function handling the request.
Example:
g.Post("/users", createUserHandler)
Example ΒΆ
This function is named ExampleGroup_Post() it with the Examples type.
q := New() // Create a route group with prefix "/api" apiGroup := q.Group("/api") // Define a POST route inside the group apiGroup.Post("/users", func(c *Ctx) error { // Return a success message return c.Status(201).String("User created") }) // Simulate a POST request to "/api/users" res, _ := q.Qtest(QuickTestOptions{ Method: MethodPost, URI: "/api/users", }) if err := res.AssertStatus(201); err != nil { fmt.Println("Status error:", err) } if err := res.AssertString("User created"); err != nil { fmt.Println("Body error:", err) } // Print the response body fmt.Println(res.BodyStr())
Output: User created
func (*Group) Put ΒΆ
func (g *Group) Put(pattern string, handlerFunc HandleFunc)
Put registers a new PUT route.
Parameters:
- pattern: The route pattern.
- handlerFunc: The function handling the request.
Example:
g.Put("/users/:id", updateUserHandler)
Example ΒΆ
This function is named ExampleGroup_Put() it with the Examples type.
q := New() // Create a route group with prefix "/api" apiGroup := q.Group("/api") // Define a PUT route inside the group apiGroup.Put("/users/:id", func(c *Ctx) error { // Return a success message return c.Status(200).String("User updated") }) // Simulate a PUT request to "/api/users/42" res, _ := q.Qtest(QuickTestOptions{ Method: MethodPut, URI: "/api/users/42", }) if err := res.AssertStatus(200); err != nil { fmt.Println("Status error:", err) } if err := res.AssertString("User updated"); err != nil { fmt.Println("Body error:", err) } // Print the response body fmt.Println(res.BodyStr())
Output: User updated
func (*Group) Use ΒΆ
Use adds middleware to the group.
This function allows adding middleware to a specific group of routes. Middleware functions are executed **before** the route handlers, allowing for request modifications, logging, authentication, etc.
Parameters:
- mw: A middleware function that modifies the HTTP handler.
Example Usage:
q := quick.New() group := q.Group("/v1") group.Get("/user", func(c *quick.Ctx) error { return c.Status(200).SendString("[GET] [GROUP] /v1/user ok!!!") })
Example ΒΆ
This function is named ExampleGroup_Delete() it with the Examples type.
// Create a new Quick instance q := New() // Create a new group with a common prefix api := q.Group("/api") // Define a simple middleware that logs requests logMiddleware := func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Println("Middleware activated for:", r.URL.Path) next.ServeHTTP(w, r) }) } // Apply middleware to the group api.Use(logMiddleware) // Define a GET route inside the group api.Get("/hello", func(c *Ctx) error { return c.Status(200).String("Hello from API group Quick") }) // Simulate a request to test middleware activation res, _ := q.Qtest(QuickTestOptions{ Method: MethodGet, URI: "/api/hello", }) if err := res.AssertStatus(200); err != nil { fmt.Println("Status error:", err) } if err := res.AssertString("Hello from API group Quick"); err != nil { fmt.Println("Body error:", err) } // Print the response body fmt.Println(res.BodyStr())
Output: Middleware activated for: /api/hello Hello from API group Quick
type HandleFunc ΒΆ
HandleFunc represents a function signature for route handlers in Quick.
This function type is used for defining request handlers within Quick's routing system. It receives a pointer to `Ctx`, which encapsulates request and response data.
Example Usage:
q.Get("/example", func(c *quick.Ctx) error { return c.Status(quick.StatusOK).SendString("Hello, Quick!") })
type Handler ΒΆ
type Handler interface { // ServeQuick processes an HTTP request in the Quick framework. // // Parameters: // - c *Ctx: The request context containing request and response details. // // Returns: // - error: Any error encountered while processing the request. ServeQuick(*Ctx) error }
Handler defines an interface that wraps the ServeQuick method.
Any type implementing `ServeQuick(*Ctx) error` can be used as a request handler in Quick. This abstraction allows for more flexible middleware and handler implementations, including struct-based handlers.
Example Usage:
type MyHandler struct{} func (h MyHandler) ServeQuick(c *quick.Ctx) error { return c.Status(quick.StatusOK).SendString("Struct-based handler") } q.Use(MyHandler{})
type HandlerFunc ΒΆ
HandlerFunc defines the function signature for request handlers in Quick.
This type provides a way to implement request handlers as standalone functions while still conforming to the `Handler` interface. It allows functions of type `HandlerFunc` to be passed as middleware or endpoint handlers.
Example Usage:
func myHandler(c *quick.Ctx) error { return c.Status(quick.StatusOK).SendString("HandlerFunc example") } q.Use(quick.HandlerFunc(myHandler))
func (HandlerFunc) ServeQuick ΒΆ
func (h HandlerFunc) ServeQuick(c *Ctx) error
ServeQuick allows a HandlerFunc to satisfy the Handler interface.
This method enables `HandlerFunc` to be used wherever a `Handler` is required by implementing the `ServeQuick` method.
Example Usage:
q.Use(quick.HandlerFunc(func(c *quick.Ctx) error { return c.Status(quick.StatusOK).SendString("Hello from HandlerFunc!") }))
func (HandlerFunc) Server ΒΆ
func (h HandlerFunc) Server(c *Ctx) error
Serve allows a HandlerFunc to satisfy the Handler interface.
This method enables `HandlerFunc` to be used wherever a `Handler` is required by implementing the `Serve` method.
Example Usage:
q.Use(quick.HandlerFunc(func(c *quick.Ctx) error { return c.Status(quick.StatusOK).SendString("Hello from HandlerFunc!") }))
type M ΒΆ
type M map[string]interface{}
M is a shortcut for map[string]interface{}, allowing `c.M{}`
type MiddlewareFunc ΒΆ
type MiddlewareFunc func(next HandlerFunc) HandlerFunc
MiddlewareFunc defines the signature for middleware functions in Quick. A middleware function receives the next HandlerFunc in the chain and returns a new HandlerFunc. Middleware can perform actions before and/or after calling the next handler.
Example:
func LoggingMiddleware() quick.MiddlewareFunc { return func(next quick.HandlerFunc) quick.HandlerFunc { return func(c *quick.Ctx) error { // Before handler logic (e.g., logging request details) log.Printf("Request received: %s %s", c.Request.Method, c.Request.URL) err := next(c) // Call the next handler // After handler logic (e.g., logging response status) log.Printf("Response sent with status: %d", c.ResponseWriter.Status()) return err } } }
type QTestPlus ΒΆ
type QTestPlus struct {
// contains filtered or unexported fields
}
QTestPlus implements QtestReturn, encapsulating HTTP response details for testing.
func (*QTestPlus) AssertBodyContains ΒΆ
AssertBodyContains checks if the response body contains the expected content.
Example Usage:
err := resp.AssertBodyContains("Success")
Returns:
- error: Returns an error if the expected content is not found in the body.
Example ΒΆ
ExampleQTestPlus_AssertBodyContains demonstrates how to validate the response body.
The "/json" route returns a JSON response, and the test verifies the presence of the "message" key.
// Creating a Quick instance q := New() // Defining a route that returns JSON q.Get("/json", func(c *Ctx) error { data := map[string]string{"message": "Hello, Quick!"} return c.JSON(data) }) // Performing the HTTP test opts := QuickTestOptions{ Method: "GET", URI: "/json", } res, err := q.Qtest(opts) if err != nil { fmt.Println("Error:", err) return } // Validating the response body err = res.AssertBodyContains(`"message":"Hello, Quick!"`) if err != nil { fmt.Println("Body assertion failed:", err) } else { fmt.Println("Body contains expected content") }
Output: Body contains expected content
func (*QTestPlus) AssertHeader ΒΆ
AssertHeader verifies if the specified header has the expected value.
Example Usage:
err := resp.AssertHeader("Content-Type", "application/json")
Returns:
- error: Returns an error if the header does not match the expected value.
Example ΒΆ
ExampleQTestPlus_AssertHeader demonstrates how to validate an HTTP response header.
The "/header" route sets an "X-Custom-Header", which is then validated.
// Creating a Quick instance q := New() // Defining a route with a custom header q.Get("/header", func(c *Ctx) error { c.Set("X-Custom-Header", "QuickFramework") return c.Status(200).String("OK") }) // Performing the HTTP test opts := QuickTestOptions{ Method: "GET", URI: "/header", } res, err := q.Qtest(opts) if err != nil { fmt.Println("Error:", err) return } // Validating the header err = res.AssertHeader("X-Custom-Header", "QuickFramework") if err != nil { fmt.Println("Header assertion failed:", err) } else { fmt.Println("Header is correct") }
Output: Header is correct
func (*QTestPlus) AssertHeaderContains ΒΆ
AssertHeaderContains checks if the specified header contains the expected substring.
Example Usage:
err := resp.AssertHeaderContains("Powered","ered")
Returns:
- error: Returns an error if the header does not match the expected value.
Example ΒΆ
ExampleQTestPlus_AssertHeaderContains demonstrates how to verify if a header contains a substring.
The simulated HTTP response includes "X-Custom" header with value "PoweredByQuick".
q := New() q.Get("/header", func(c *Ctx) error { c.Set("X-Custom", "PoweredByQuick") return c.String("OK") }) res, _ := q.Qtest(QuickTestOptions{ Method: "GET", URI: "/header", }) err := res.AssertHeaderContains("X-Custom", "Quick") if err != nil { fmt.Println("Assertion failed:", err) } else { fmt.Println("Header contains expected substring") }
Output: Header contains expected substring
func (*QTestPlus) AssertHeaderHasPrefix ΒΆ
AssertHeaderHasPrefix checks if the specified header starts with the expected prefix.
Example Usage:
err := resp.AssertHeaderHasPrefix("Powered")
Returns:
- error: Returns an error if the header does not match the expected value.
Example ΒΆ
ExampleQTestPlus_AssertHeaderHasPrefix demonstrates how to verify if a header starts with a prefix.
The simulated HTTP response includes "X-Version" header with value "v1.2.3".
q := New() q.Get("/prefix", func(c *Ctx) error { c.Set("X-Version", "v1.2.3") return c.String("OK") }) res, _ := q.Qtest(QuickTestOptions{ Method: "GET", URI: "/prefix", }) err := res.AssertHeaderHasPrefix("X-Version", "v1") if err != nil { fmt.Println("Assertion failed:", err) } else { fmt.Println("Header has expected prefix") }
Output: Header has expected prefix
func (*QTestPlus) AssertHeaderHasValueInSet ΒΆ
AssertHeaderHasValueInSet checks if the specified header value is one of the allowed values.
Example Usage:
err := resp.AssertHeaderHasValueInSet("Powered",[]string{""})
Returns:
- error: Returns an error if the header does not match the expected value.
Example ΒΆ
ExampleQTestPlus_AssertHeaderHasValueInSet demonstrates how to verify if a header value matches one of the allowed values.
The simulated HTTP response includes "X-Env" header with value "staging".
q := New() q.Get("/variant", func(c *Ctx) error { c.Set("X-Env", "staging") return c.String("OK") }) res, _ := q.Qtest(QuickTestOptions{ Method: "GET", URI: "/variant", }) err := res.AssertHeaderHasValueInSet("X-Env", []string{"dev", "staging", "prod"}) if err != nil { fmt.Println("Assertion failed:", err) } else { fmt.Println("Header value is in allowed set") }
Output: Header value is in allowed set
func (*QTestPlus) AssertNoHeader ΒΆ
AssertNoHeader checks if the specified header is not present or empty.
Example Usage:
err := resp.AssertNoHeader("X-Powered-By")
Returns:
- error: Returns an error if the header does not match the expected value.
Example ΒΆ
ExampleQTestPlus_AssertNoHeader demonstrates how to check that a header is not present in the response.
The simulated HTTP response does not include the "X-Powered-By" header.
q := New() q.Get("/no-header", func(c *Ctx) error { return c.String("No custom header here.") }) res, err := q.Qtest(QuickTestOptions{ Method: "GET", URI: "/no-header", }) if err != nil { fmt.Println("Error:", err) return } err = res.AssertNoHeader("X-Powered-By") if err != nil { fmt.Println("Assertion failed:", err) } else { fmt.Println("Header is not present as expected") }
Output: Header is not present as expected
func (*QTestPlus) AssertStatus ΒΆ
AssertStatus verifies if the response status matches the expected status.
Example Usage:
err := resp.AssertStatus(200) if err != nil { t.Errorf("Unexpected status: %v", err) }
Returns:
- error: Returns an error if the expected status does not match the actual status.
Example ΒΆ
ExampleQTestPlus_AssertStatus demonstrates how to verify the response status code.
The "/notfound" route returns a 404 status, which is validated in the assertion.
// Creating a Quick instance q := New() // Defining a route that returns 404 q.Get("/notfound", func(c *Ctx) error { return c.Status(404).String("Not Found") }) // Performing the HTTP test opts := QuickTestOptions{ Method: "GET", URI: "/notfound", } res, err := q.Qtest(opts) if err != nil { fmt.Println("Error:", err) return } // Validating the response status err = res.AssertStatus(404) if err != nil { fmt.Println("Assertion failed:", err) } else { fmt.Println("Status code is correct") }
Output: Status code is correct
func (*QTestPlus) AssertString ΒΆ
AssertString compares the response body to the expected string.
Example Usage:
err := resp.AssertString("pong")
Returns:
- error: Returns an error if the header does not match the expected value.
Example ΒΆ
ExampleQTestPlus_AssertString demonstrates how to compare the response body with an expected string.
The simulated HTTP response body contains "pong".
q := New() q.Get("/ping", func(c *Ctx) error { return c.String("pong") }) res, _ := q.Qtest(QuickTestOptions{ Method: "GET", URI: "/ping", }) err := res.AssertString("pong") if err != nil { fmt.Println("Assertion failed:", err) } else { fmt.Println("Body matches expected string") }
Output: Body matches expected string
func (*QTestPlus) Body ΒΆ
Body returns the response body as a byte slice.
Returns:
- []byte: The response body.
Example ΒΆ
ExampleQTestPlus_Body demonstrates how to retrieve the response body as a byte slice.
The simulated response object contains "Hello, Quick!" as its body content.
// Simulating a response object with a predefined body res := &QTestPlus{ body: []byte("Hello, Quick!"), } // Retrieving and printing the body content fmt.Println(string(res.Body()))
Output: Hello, Quick!
func (*QTestPlus) BodyStr ΒΆ
BodyStr returns the response body as a string.
Returns:
- string: The response body as a string.
Example ΒΆ
ExampleQTestPlus_BodyStr demonstrates how to retrieve the response body as a string.
The simulated response object contains "Hello, Quick!" as its body content.
// Simulating a response object with a predefined body res := &QTestPlus{ bodyStr: "Hello, Quick!", } // Retrieving and printing the body content as a string fmt.Println(res.BodyStr())
Output: Hello, Quick!
func (*QTestPlus) Response ΒΆ
Response returns the raw *http.Response for advanced validation.
Returns:
- *http.Response: The full HTTP response object.
Example ΒΆ
ExampleQTestPlus_Response demonstrates how to retrieve the complete HTTP response object.
The simulated HTTP response object contains a status of "200 OK".
// Simulating an HTTP response object httpResponse := &http.Response{ Status: "200 OK", StatusCode: 200, } // Simulating a response object containing the HTTP response res := &QTestPlus{ response: httpResponse, } // Retrieving and printing the response status fmt.Println("Response Status:", res.Response().Status)
Output: Response Status: 200 OK
func (*QTestPlus) StatusCode ΒΆ
StatusCode retrieves the HTTP status code of the response.
Returns:
- int: The HTTP status code.
Example ΒΆ
ExampleQTestPlus_StatusCode demonstrates how to retrieve the response status code.
The simulated response object contains a status code of 200.
res := &QTestPlus{ statusCode: 200, } // Retrieving and printing the response status code fmt.Println("Status Code:", res.StatusCode())
Output: Status Code: 200
type QtestReturn ΒΆ
type QtestReturn interface { Body() []byte BodyStr() string StatusCode() int Response() *http.Response AssertStatus(expected int) error AssertHeader(key, expectedValue string) error AssertNoHeader(key string) error AssertString(expected string) error AssertBodyContains(expected any) error AssertHeaderHasValueInSet(key string, allowed []string) error AssertHeaderHasPrefix(key, prefix string) error AssertHeaderContains(key, substring string) error }
QtestReturn defines an interface for validating HTTP test responses.
This interface provides methods to retrieve response details such as body, status code, headers, and to perform assertions for testing HTTP responses.
Example Usage:
resp, err := q.Qtest(quick.QuickTestOptions{ Method: quick.MethodGet, URI: "/test", }) if err != nil { log.Fatal(err) } if err := resp.AssertStatus(200); err != nil { log.Fatal(err) }
type Quick ΒΆ
type Quick struct { Cors bool // Indicates if CORS is enabled. CorsSet func(http.Handler) http.Handler // CORS middleware handler function. CorsOptions map[string]string // CORS options map // contains filtered or unexported fields }
Quick is the main structure of the framework, holding routes and configurations.
func New ΒΆ
New creates a new instance of the Quick structure to manage HTTP routes and handlers.
This function initializes a Quick instance with optional configurations provided through the `Config` parameter. If no configuration is provided, it uses the `defaultConfig`.
Parameters:
- c ...Config: (Optional) Configuration settings for customizing the Quick instance.
Returns:
- *Quick: A pointer to the initialized Quick instance.
Example Usage:
// Basic usage - Create a default Quick instance q := quick.New() // Custom usage - Create a Quick instance with specific configurations q := quick.New(quick.Config{ RouteCapacity: 500, }) q.Get("/", func(c quick.Ctx) error { return c.SendString("Hello, Quick!") })
Example ΒΆ
This function is named ExampleNew() it with the Examples type.
// Start Quick instance q := New() // Define a simple GET route q.Get("/", func(c *Ctx) error { // Set response header c.Set("Content-Type", "text/plain") // Return a text response return c.Status(200).String("Quick in action β€οΈ!") }) // Simulate a request using Quick's test utility res, _ := q.Qtest(QuickTestOptions{ Method: MethodGet, URI: "/", Headers: map[string]string{"Content-Type": "application/json"}, }) if err := res.AssertStatus(200); err != nil { fmt.Println("status error:", err) } if err := res.AssertString("Quick in action β€οΈ!"); err != nil { fmt.Println("body error:", err) } fmt.Println(res.BodyStr())
Output: Quick in action β€οΈ!
func (*Quick) Any ΒΆ
func (q *Quick) Any(path string, handlerFunc HandleFunc)
Any registers the same handlerFunc for all standard HTTP methods (GET, POST, PUT, etc.).
This is useful when you want to attach a single handler to a path regardless of the HTTP method, and handle method-based logic inside the handler itself (e.g., returning 405 if not GET).
Example:
app := quick.New() app.Any("/health", func(c *quick.Ctx) error { if c.Method() != quick.MethodGet { return c.Status(quick.StatusMethodNotAllowed).SendString("Method Not Allowed") } return c.Status(quick.StatusOK).SendString("OK") })
Note: The handlerFunc will be registered individually for each method listed in allMethods.
func (*Quick) Delete ΒΆ
func (q *Quick) Delete(pattern string, handlerFunc HandleFunc)
Delete registers an HTTP route with the DELETE method on the Quick server.
This function associates a DELETE request with a specific route pattern and handler function. It is typically used for deleting existing resources.
Parameters:
- pattern string: The route pattern (e.g., "/users/:id").
- handlerFunc HandleFunc: The function that will handle the DELETE request.
Example Usage:
// This function is automatically triggered when defining a DELETE route in Quick.
Example ΒΆ
This function is named ExampleQuick_Delete() it with the Examples type.
// Start Quick instance q := New() // Define a DELETE route q.Delete("/delete", func(c *Ctx) error { // Return response indicating resource deletion return c.Status(200).String("Deleted resource!") }) // Simulate a DELETE request for testing res, _ := q.Qtest(QuickTestOptions{ Method: MethodDelete, URI: "/delete", Headers: map[string]string{"Content-Type": "application/json"}, }) if err := res.AssertStatus(200); err != nil { fmt.Println("status error:", err) } if err := res.AssertString("Deleted resource!"); err != nil { fmt.Println("body error:", err) } fmt.Println(res.BodyStr())
Output: Deleted resource!
func (*Quick) Display ΒΆ
Display prints a styled startup banner to the console showing essential information about the Quick server.
It includes the following details:
- The current version of Quick
- Host and port where the server is running
- The total number of registered routes
The banner is only printed if the `NoBanner` option is set to false in the configuration.
Parameters:
- scheme: The protocol used by the server (e.g., "http" or "https").
- addr: The address the server is bound to (in the format "host:port").
func (*Quick) Get ΒΆ
func (q *Quick) Get(pattern string, handlerFunc HandleFunc)
Get registers an HTTP route with the GET method on the Quick server.
This function associates a GET request with a specific route pattern and handler function. It ensures that the request is properly processed when received.
Parameters:
- pattern string: The route pattern (e.g., "/users/:id").
- handlerFunc HandleFunc: The function that will handle the GET request.
Example Usage:
// This function is automatically triggered when defining a GET route in Quick.
Example ΒΆ
This function is named ExampleQuick_Get() it with the Examples type.
// Start Quick instance q := New() // Define a GET route with a handler function q.Get("/hello", func(c *Ctx) error { // Return a simple text response return c.Status(200).String("Hello, world!") }) // Simulate a GET request to the route res, _ := q.Qtest(QuickTestOptions{ Method: MethodGet, URI: "/hello", }) if err := res.AssertStatus(200); err != nil { fmt.Println("status error:", err) } if err := res.AssertString("Hello, world!"); err != nil { fmt.Println("body error:", err) } fmt.Println(res.BodyStr())
Output: Hello, world!
func (*Quick) GetRoute ΒΆ
GetRoute retrieves all registered routes in the Quick framework.
This function returns a slice containing all the routes that have been registered in the Quick instance. It is useful for debugging, logging, or dynamically inspecting available routes.
Example Usage:
routes := q.GetRoute() for _, route := range routes { fmt.Println("Method:", route.Method, "Path:", route.Path) }
Returns:
- []*Route: A slice of pointers to the registered Route instances.
Example ΒΆ
This function is named ExampleQuick_GetRoute() it with the Examples type.
// Start Quick instance q := New() // Define multiple routes q.Get("/users/:id", func(c *Ctx) error { return c.Status(200).String("User ID: " + c.Params["id"]) }) q.Post("/users", func(c *Ctx) error { return c.Status(201).String("User created") }) // Get a list of all registered routes routes := q.GetRoute() // Print the total number of routes fmt.Println(len(routes)) // Iterate over the routes and print their method and pattern for _, route := range routes { fmt.Println(route.Method, route.Pattern) }
Output: 2 GET /users/:id POST
func (*Quick) Group ΒΆ
Group creates a new route group with a shared prefix.
This function allows organizing routes under a common prefix, making it easier to manage related endpoints (e.g., `/api`, `/v1`, `/admin`). All routes registered within this group will automatically inherit the specified prefix.
Grouping routes is useful for:
- API versioning (`/v1`, `/v2`).
- Organizing authentication-protected routes (`/auth`, `/admin`).
- Applying shared middlewares to a set of routes.
Parameters:
- prefix: The common prefix for all routes in this group.
Returns:
- *Group: A new Group instance that can be used to define related routes.
Example Usage:
group := q.Group("/api") group.Get("/user", func(c *quick.Ctx) error { return c.Status(200).SendString("[GET] [GROUP] /v1/user ok!!!") })
Example ΒΆ
This function is named ExampleQuick_Group() it with the Examples type.
q := New() // Create a route group with prefix "/api" apiGroup := q.Group("/api") // As the prefix field is unexported, we test by registering a route and calling it apiGroup.Get("/check", func(c *Ctx) error { return c.Status(200).String("Prefix OK") }) res, _ := q.Qtest(QuickTestOptions{ Method: MethodGet, URI: "/api/check", }) if err := res.AssertStatus(200); err != nil { fmt.Println("Status error:", err) } if err := res.AssertString("Prefix OK"); err != nil { fmt.Println("Body error:", err) } fmt.Println(res.BodyStr())
Output: Prefix OK
func (*Quick) Handler ΒΆ
Handler returns the main HTTP handler for Quick, allowing integration with standard http.Server and testing frameworks.
func (*Quick) HandlerFunc ΒΆ
func (q *Quick) HandlerFunc(h HandlerFunc) http.HandlerFunc
HandlerFunc adapts a quick.HandlerFunc to a standard http.HandlerFunc. It creates a new Quick context (Ctx) for each HTTP request, allowing Quick handlers to access request and response objects seamlessly.
Usage Example:
http.HandleFunc(\"/\", app.HandlerFunc(func(c *quick.Ctx) error { return c.Status(200).JSON(map[string]string{\"message\": \"Hello, Quick!\"}) }))
func (*Quick) HandlersCount ΒΆ
GetRoute retrieves all registered routes in the Quick framework.
This function returns a slice containing all the routes that have been registered in the Quick instance. It is useful for debugging, logging, or dynamically inspecting available routes.
Example Usage:
routes := q.GetRoute() for _, route := range routes { fmt.Println("Method:", route.Method, "Path:", route.Path) }
Returns:
- []*Route: A slice of pointers to the registered Route instances.
func (*Quick) Head ΒΆ
func (q *Quick) Head(pattern string, handlerFunc HandleFunc)
Head registers an HTTP route with the HEAD method on the Quick server.
This function associates a HEAD request with a specific route pattern and handler function. It ensures that the request is properly processed according to the HTTP HEAD specification, meaning that only headers and the status code are sent in the response, with no response body.
Parameters:
- pattern string: The route pattern (e.g., "/users/:id").
- handlerFunc HandleFunc: The function that will handle the HEAD request.
Example Usage:
// This function is automatically triggered when defining a HEAD route in Quick.
func (*Quick) Listen ΒΆ
Listen starts the Quick server and blocks indefinitely.
This function initializes the HTTP server and prevents the application from exiting.
Example Usage:
q.Listen(":8080")
Parameters:
- addr: The address on which the server should listen (e.g., ":8080").
- handler: (Optional) Custom HTTP handlers.
Returns:
- error: Any errors encountered while starting the server.
Example ΒΆ
This function is named ExampleQuick_Listen() it with the Examples type.
// Start Quick instance q := New() // Define a simple route q.Get("/", func(c *Ctx) error { return c.Status(200).String("Hello, Quick!") }) // Start the server and listen on port 8080 err := q.Listen(":8080") if err != nil { fmt.Println("Error starting server:", err) } // (This function starts a server and does not return an output directly)
func (*Quick) ListenTLS ΒΆ
func (q *Quick) ListenTLS(addr, certFile, keyFile string, useHTTP2 bool, handler ...http.Handler) error
ListenTLS starts an HTTPS server on the specified address using the provided certificate and key files. It allows enabling or disabling HTTP/2 support. It also configures basic modern TLS settings, sets up a listener with SO_REUSEPORT (when possible), and applies a graceful shutdown procedure.
Parameters:
- addr: the TCP network address to listen on (e.g., ":443")
- certFile: the path to the SSL certificate file
- keyFile: the path to the SSL private key file
- useHTTP2: whether or not to enable HTTP/2
- handler: optional HTTP handlers. If none is provided, the default handler is used.
Returns:
- error: an error if something goes wrong creating the listener or starting the server.
func (*Quick) ListenWithShutdown ΒΆ
func (q *Quick) ListenWithShutdown(addr string, handler ...http.Handler) (*http.Server, func(), error)
ListenWithShutdown starts an HTTP server and returns both the server instance and a shutdown function.
This method initializes performance tuning settings, creates a TCP listener, and starts the server in a background goroutine. The returned shutdown function allows for a graceful termination of the server.
Parameters:
- addr: The address (host:port) where the server should listen.
- handler: Optional HTTP handlers that can be provided to the server.
Returns:
- *http.Server: A reference to the initialized HTTP server.
- func(): A shutdown function to gracefully stop the server.
- error: Any error encountered during the server setup.
func (*Quick) Options ΒΆ
func (q *Quick) Options(pattern string, handlerFunc HandleFunc)
Options registers an HTTP route with the OPTIONS method on the Quick server.
This function associates an OPTIONS request with a specific route pattern and handler function. OPTIONS requests are typically used to determine the allowed HTTP methods for a resource.
Parameters:
- pattern string: The route pattern (e.g., "/users").
- handlerFunc HandleFunc: The function that will handle the OPTIONS request.
Example Usage:
// This function is automatically triggered when defining an OPTIONS route in Quick.
Example ΒΆ
This function is named ExampleQuick_Options()
it with the Examples type.
// Start Quick instance q := New() // Define an OPTIONS route q.Options("/resource", func(c *Ctx) error { c.Set("Allow", "GET, POST, OPTIONS") return c.Status(204).Send(nil) // No Content response }) // Simulate an OPTIONS request to "/resource" res, _ := q.Qtest(QuickTestOptions{ Method: MethodOptions, URI: "/resource", }) // Print the response status fmt.Println("Status:", res.StatusCode())
Output: Status: 204
func (*Quick) Patch ΒΆ
func (q *Quick) Patch(pattern string, handlerFunc HandleFunc)
Patch registers an HTTP route with the PATCH method on the Quick server.
This function associates a PATCH request with a specific route pattern and handler function. It is typically used for applying partial updates to an existing resource.
Parameters:
- pattern string: The route pattern (e.g., "/users/:id").
- handlerFunc HandleFunc: The function that will handle the PATCH request.
Example Usage:
// This function is automatically triggered when defining a PATCH route in Quick.
Example ΒΆ
This function is named ExampleQuick_Patch()
it with the Examples type.
// Start Quick instance q := New() // Define a PATCH route q.Patch("/update", func(c *Ctx) error { return c.Status(200).String("PATCH request received") }) // Simulate a PATCH request to "/update" res, _ := q.Qtest(QuickTestOptions{ Method: MethodPatch, URI: "/update", }) if err := res.AssertStatus(200); err != nil { fmt.Println("status error:", err) } if err := res.AssertString("PATCH request received"); err != nil { fmt.Println("body error:", err) } fmt.Println(res.BodyStr())
Output: PATCH request received
func (*Quick) Post ΒΆ
func (q *Quick) Post(pattern string, handlerFunc HandleFunc)
Post registers an HTTP route with the POST method on the Quick server.
This function associates a POST request with a specific route pattern and handler function. It is typically used for handling form submissions, JSON payloads, or data creation.
Parameters:
- pattern string: The route pattern (e.g., "/users").
- handlerFunc HandleFunc: The function that will handle the POST request.
Example Usage:
// This function is automatically triggered when defining a POST route in Quick.
Example ΒΆ
This function is named ExampleQuick_Post() it with the Examples type.
// Start Quick instance q := New() // Define a POST route q.Post("/create", func(c *Ctx) error { // Return response indicating resource creation return c.Status(201).String("Resource created!") }) // Simulate a POST request for testing res, _ := q.Qtest(QuickTestOptions{ Method: MethodPost, URI: "/create", Headers: map[string]string{"Content-Type": "application/json"}, }) if err := res.AssertStatus(201); err != nil { fmt.Println("status error:", err) } if err := res.AssertString("Resource created!"); err != nil { fmt.Println("body error:", err) } fmt.Println(res.BodyStr())
Output: Resource created!
func (*Quick) Put ΒΆ
func (q *Quick) Put(pattern string, handlerFunc HandleFunc)
Put registers an HTTP route with the PUT method on the Quick server.
This function associates a PUT request with a specific route pattern and handler function. It is typically used for updating existing resources.
Parameters:
- pattern string: The route pattern (e.g., "/users/:id").
- handlerFunc HandleFunc: The function that will handle the PUT request.
Example Usage:
// This function is automatically triggered when defining a PUT route in Quick.
Example ΒΆ
This function is named ExampleQuick_Put() it with the Examples type.
// Start Quick instance q := New() // Define a PUT route q.Put("/update", func(c *Ctx) error { // Return response indicating resource update return c.Status(200).String("Update resource!") }) // Simulate a PUT request for testing res, _ := q.Qtest(QuickTestOptions{ Method: MethodPut, URI: "/update", Headers: map[string]string{"Content-Type": "application/json"}, }) if err := res.AssertStatus(200); err != nil { fmt.Println("status error:", err) } if err := res.AssertString("Update resource!"); err != nil { fmt.Println("body error:", err) } fmt.Println(res.BodyStr())
Output: Update resource!
func (Quick) Qtest ΒΆ
func (q Quick) Qtest(opts QuickTestOptions) (QtestReturn, error)
Qtest performs an HTTP request using QuickTestOptions and returns a response handler.
This method executes a test HTTP request within the Quick framework, allowing validation of the response status, headers, and body.
Example Usage:
resp, err := q.Qtest(quick.QuickTestOptions{ Method: quick.MethodGet, URI: "/test", }) if err != nil { log.Fatal(err) } if err := resp.AssertStatus(200); err != nil { log.Fatal(err) }
Returns:
- QtestReturn: An interface for response validation
- error: Error encountered during request execution, if any.
Example ΒΆ
ExampleQuick_Qtest demonstrates how to use Qtest to test a simple GET route.
The "/hello" route returns a response with status 200 and body "Hello, Quick!".
// Creating a Quick instance q := New() // Defining a simple GET route q.Get("/hello", func(c *Ctx) error { return c.Status(200).String("Hello, Quick!") }) // Defining the request parameters opts := QuickTestOptions{ Method: "GET", URI: "/hello", } // Performing the HTTP test using the Quick instance res, err := q.Qtest(opts) // Handling errors if err != nil { fmt.Println("Error:", err) return } // Printing response details fmt.Println("Status Code:", res.StatusCode()) fmt.Println("Body:", res.BodyStr())
Output: Status Code: 200 Body: Hello, Quick!
func (*Quick) ServeHTTP ΒΆ
func (q *Quick) ServeHTTP(w http.ResponseWriter, req *http.Request)
ServeHTTP processes incoming HTTP requests and matches them to registered routes.
This function efficiently routes HTTP requests to the appropriate handler while leveraging a **pooled response writer** and **context pooling** to minimize memory allocations and improve performance.
If the request method is `OPTIONS`, it is handled separately via `handleOptions`. If no matching route is found, the function responds with `404 Not Found`.
Example Usage: This function is automatically invoked by the `http.Server` when a request reaches the Quick router.
Example ΒΆ
This function is named ExampleQuick_ServeHTTP() it with the Examples type.
// Start Quick instance q := New() // Define a route with a dynamic parameter q.Get("/users/:id", func(c *Ctx) error { // Retrieve the parameter and return it in the response return c.Status(200).String("User Id: " + c.Params["id"]) }) // Simulate a request with a user ID res, _ := q.Qtest(QuickTestOptions{ Method: MethodGet, URI: "/users/42", }) if err := res.AssertStatus(200); err != nil { fmt.Println("status error:", err) } if err := res.AssertString("User Id: 42"); err != nil { fmt.Println("body error:", err) } // Print the response body fmt.Println(res.BodyStr())
Output: User Id: 42
func (*Quick) Shutdown ΒΆ
Shutdown gracefully shuts down the Quick server without interrupting active connections.
This function ensures that all ongoing requests are completed before shutting down, preventing abrupt connection termination.
Example Usage:
q := quick.New() q.Get("/", func(c *quick.Ctx) error { return c.SendString("Server is running!") }) q.Shutdown()
Returns:
- error: Any errors encountered during shutdown.
Example ΒΆ
This function is named ExampleQuick_Shutdown()
it with the Examples type.
// Create a new Quick instance q := New() // Define a GET route with a handler function q.Get("/", func(c *Ctx) error { // Return a simple text response return c.SendString("Server is running!") }) // Simulate a GET request to the route and capture the response res, _ := q.Qtest(QuickTestOptions{ Method: MethodGet, URI: "/", }) if err := res.AssertStatus(200); err != nil { fmt.Println("status error:", err) } // Print only the response body to match GoDoc expectations fmt.Println(res.BodyStr()) // Simulate server shutdown immediately after starting err := q.Shutdown() // Print the shutdown status if err == nil { fmt.Println("Server shut down successfully.") } else { fmt.Println("Error shutting down server:", err) }
Output: Server is running! Server shut down successfully.
func (*Quick) Static ΒΆ
Static serves static files (HTML, CSS, JS, images, etc.) from a directory or embedded filesystem.
This function allows you to register a static file server in the Quick framework, either using a local directory (`string`) or an embedded filesystem (`embed.FS`). By embedding files, they become part of the binary at compile time, eliminating the need for external file access.
Example Usage: This function is useful for serving front-end assets or static resources directly from the Go application. It supports both local directories and embedded files.
Parameters:
- route: The base path where static files will be served (e.g., "/static").
- dirOrFS: The source of the static files. It accepts either:
- `string`: A local directory path (e.g., `"./static"`).
- `embed.FS`: An embedded file system for compiled-in assets.
Returns:
- None (void function).
Notes:
- The function automatically trims trailing slashes from `route`.
- If an invalid parameter is provided, the function panics.
- When using an embedded filesystem, files are served directly from memory.
Example ΒΆ
// Quick Start q := New() q.Static("/static", staticFilesExample) q.Get("/", func(c *Ctx) error { c.File("static/index.html") return nil }) // Simulates a request for "/" res, _ := q.Qtest(QuickTestOptions{ Method: MethodGet, URI: "/", }) if err := res.AssertStatus(200); err != nil { fmt.Println("status error:", err) } fmt.Println("Status:", res.StatusCode())
Output: Status: 200
func (*Quick) Use ΒΆ
Use function adds middleware to the Quick server, with special treatment for CORS.
This method allows adding custom middleware functions to process requests before they reach the final handler. If a CORS middleware is detected, it is automatically applied.
Parameters:
- mw any: Middleware function to be added. It must be of type `func(http.Handler) http.Handler`.
Example Usage:
q := quick.New() q.Use(maxbody.New(50000)) q.Post("/v1/user/maxbody/any", func(c *quick.Ctx) error { c.Set("Content-Type", "application/json")// return c.Status(200).Send(c.Body()) })
Example ΒΆ
This function is named ExampleQuick_Use() it with the Examples type.
// Start Quick instance q := New() // Apply CORS middleware to allow cross-origin requests q.Use(cors.New()) // Define a route that will be affected by the middleware q.Get("/use", func(c *Ctx) error { // Set response header c.Set("Content-Type", "text/plain") // Return response with middleware applied return c.Status(200).String("Quick in action com middleware β€οΈ!") }) // Simulate a request for testing res, _ := q.Qtest(QuickTestOptions{ Method: MethodGet, URI: "/use", Headers: map[string]string{"Content-Type": "application/json"}, }) if err := res.AssertStatus(200); err != nil { fmt.Println("status error:", err) } if err := res.AssertString("Quick in action com middleware β€οΈ!"); err != nil { fmt.Println("body error:", err) } fmt.Println(res.BodyStr())
Output: Quick in action com middleware β€οΈ!
type QuickMockCtx ΒΆ
type QuickMockCtx interface { Get(URI string) error Post(URI string, body []byte) error Put(URI string, body []byte) error Delete(URI string) error }
QuickMockCtx defines the interface for mocking HTTP methods in Quick.
func QuickMockCtxJSON ΒΆ
func QuickMockCtxJSON(ctx *Ctx, params map[string]string) QuickMockCtx
QuickMockCtxJSON creates a new mock context for JSON content type.
func QuickMockCtxXML ΒΆ
func QuickMockCtxXML(ctx *Ctx, params map[string]string, contentType string) QuickMockCtx
QuickMockCtxXML creates a new mock context for XML content type.
type QuickMockTestServer ΒΆ
type QuickMockTestServer struct { Client *http.Client // HTTP client to interact with the mock server. Port int // Port on which the mock server runs. URI string // The request URI for the test. Method string // The HTTP method (GET, POST, etc.). Headers map[string]string // Headers to be included in the request. Body []byte // Request body content. }
QuickMockTestServer defines a mock server configuration for testing.
type QuickTestOptions ΒΆ
type QuickTestOptions struct { Method string // HTTP method (e.g., "GET", "POST") URI string // Target URI for the request Headers map[string]string // Request headers QueryParams map[string]string // Query parameters to append to the URI Body []byte // Request body payload Cookies []*http.Cookie // Cookies to include in the request LogDetails bool // Enable logging of request and response details TLS bool // Enable tls connects }
QuickTestOptions defines configuration options for executing an HTTP test request.
Example Usage:
opts := quick.QuickTestOptions{ Method: quick.MethodPost, URI: "/submit", Headers: map[string]string{"Content-Type": "application/json"}, QueryParams: map[string]string{"id": "123"}, Body: []byte(`{"name":"John Doe"}`), } resp, err := q.Qtest(opts)
type QuickTestReturn ΒΆ
type QuickTestReturn interface { Body() []byte // Returns the raw response body as a byte slice. BodyStr() string // Returns the response body as a string. StatusCode() int // Returns the HTTP status code. Response() *http.Response // Returns the full HTTP response object. }
QuickTestReturn defines the interface for handling HTTP test responses.
type Route ΒΆ
type Route struct { Group string // Route group for organization Pattern string // URL pattern associated with the route Path string // The registered path for the route Params string // Parameters extracted from the URL Method string // HTTP method associated with the route (GET, POST, etc.) // contains filtered or unexported fields }
Route represents a registered HTTP route in the Quick framework
type UploadedFile ΒΆ
type UploadedFile struct { File multipart.File Multipart *multipart.FileHeader Info FileInfo }
UploadedFile holds details of an uploaded file.
Fields:
- File: The uploaded file as a multipart.File.
- Multipart: The file header containing metadata about the uploaded file.
- Info: Additional information about the file, including filename, size, and content type.
func (*UploadedFile) Bytes ΒΆ
func (uf *UploadedFile) Bytes() []byte
Bytes returns the raw content of the uploaded file as a byte slice.
This function allows access to the file data in memory before saving it.
Returns:
- []byte: The raw bytes of the uploaded file.
Example ΒΆ
This function is named ExampleUploadedFile_Bytes() it with the Examples type.
// Start a new Quick instance q := New() // Define a POST route for file upload q.Post("/upload", func(c *Ctx) error { // Set file upload size limit c.FormFileLimit("10MB") // Retrieve the uploaded file uploadedFile, err := c.FormFile("file") if err != nil { return c.Status(400).JSON(Msg{ Msg: "Upload error", Error: err.Error(), }) } // Print only the file name fmt.Println(uploadedFile.FileName()) // Return JSON response with the file name return c.Status(200).JSON(map[string]string{ "name": uploadedFile.FileName(), }) }) // Creating an UploadedFile object with content as bytes uploadedFile := &UploadedFile{ Info: FileInfo{ Bytes: []byte("Hello, Quick!"), }, } // Converting bytes to a string to display the content fmt.Println(string(uploadedFile.Bytes()))
Output: Hello, Quick!
func (*UploadedFile) ContentType ΒΆ
func (uf *UploadedFile) ContentType() string
ContentType returns the MIME type of the uploaded file.
This function retrieves the detected content type of the uploaded file.
Returns:
- string: The MIME type of the file.
Example ΒΆ
This function is named ExampleUploadedFile_ContentType() it with the Examples type.
// Start a new Quick instance q := New() // Define a POST route for file upload q.Post("/upload", func(c *Ctx) error { // Set file upload size limit c.FormFileLimit("10MB") // Retrieve the uploaded file uploadedFile, err := c.FormFile("file") if err != nil { return c.Status(400).JSON(Msg{ Msg: "Upload error", Error: err.Error(), }) } // Print only the file name fmt.Println(uploadedFile.FileName()) // Return JSON response with the file name return c.Status(200).JSON(map[string]string{ "name": uploadedFile.FileName(), }) }) // Creating an UploadedFile object simulating an uploaded PNG file uploadedFile := &UploadedFile{ Info: FileInfo{ ContentType: "image/png", }, } // Retrieving the content type fmt.Println(uploadedFile.ContentType())
Output: image/png
func (*UploadedFile) FileName ΒΆ
func (uf *UploadedFile) FileName() string
FileName returns the name of the uploaded file.
This function retrieves the original filename as provided during the upload.
Returns:
- string: The name of the uploaded file.
Example ΒΆ
This function is named ExampleUploadedFile_FileName() it with the Examples type.
// Start a new Quick instance q := New() // Define a POST route for file upload q.Post("/upload", func(c *Ctx) error { // Set file upload size limit c.FormFileLimit("10MB") // Retrieve the uploaded file uploadedFile, err := c.FormFile("file") if err != nil { return c.Status(400).JSON(Msg{ Msg: "Upload error", Error: err.Error(), }) } // Print only the file name fmt.Println(uploadedFile.FileName()) // Return JSON response with the file name return c.Status(200).JSON(map[string]string{ "name": uploadedFile.FileName(), }) }) // Simulate an UploadedFile manually (standalone example) uploadedFile := &UploadedFile{ Info: FileInfo{ Filename: "quick.txt", }, } // Print only the file name fmt.Println(uploadedFile.FileName())
Output: quick.txt
func (*UploadedFile) Save ΒΆ
func (uf *UploadedFile) Save(destination string, nameFile ...string) error
Save stores the uploaded file in the specified directory.
If a filename is provided, the file will be saved with that name. Otherwise, the original filename is used.
Parameters:
- destination (string): The directory where the file should be saved.
- nameFile (optional []string): Custom filename (optional).
Returns:
- error: An error if the save operation fails.
Example Usage:
err := uploadedFile.Save("./uploads", "newfile.png") if err != nil { log.Fatal("Failed to save file:", err) }
Example ΒΆ
This function is named ExampleUploadedFile_Save() it with the Examples type.
// Start a new Quick instance q := New() // Define a POST route for file upload q.Post("/upload", func(c *Ctx) error { // Set file upload size limit c.FormFileLimit("10MB") // Retrieve the uploaded file uploadedFile, err := c.FormFile("file") if err != nil { return c.Status(400).JSON(Msg{ Msg: "Upload error", Error: err.Error(), }) } // Print only the file name fmt.Println(uploadedFile.FileName()) // Return JSON response with the file name return c.Status(200).JSON(map[string]string{ "name": uploadedFile.FileName(), }) }) // Creating an UploadedFile object simulating an uploaded file uploadedFile := &UploadedFile{ Info: FileInfo{ Filename: "quick.txt", Bytes: []byte("Hello, Quick!"), }, } // Saving the file to the "uploads" directory err := uploadedFile.Save("uploads") // Checking for errors if err != nil { fmt.Println("Error saving file:", err) } else { fmt.Println("File saved successfully!") }
Output: File saved successfully!
func (*UploadedFile) Size ΒΆ
func (uf *UploadedFile) Size() int64
Size returns the size of the uploaded file in bytes.
This function retrieves the file size based on the uploaded file metadata.
Returns:
- int64: The size of the file in bytes.
Example ΒΆ
This function is named ExampleUploadedFile_Size() it with the Examples type.
// Start a new Quick instance q := New() // Define a POST route for file upload q.Post("/upload", func(c *Ctx) error { // Set file upload size limit c.FormFileLimit("10MB") // Retrieve the uploaded file uploadedFile, err := c.FormFile("file") if err != nil { return c.Status(400).JSON(Msg{ Msg: "Upload error", Error: err.Error(), }) } // Print only the file name fmt.Println(uploadedFile.FileName()) // Return JSON response with the file name return c.Status(200).JSON(map[string]string{ "name": uploadedFile.FileName(), }) }) // Creating an UploadedFile object simulating an uploaded file of 2048 bytes uploadedFile := &UploadedFile{ Info: FileInfo{ Size: 2048, }, } // Retrieving the file size fmt.Println(uploadedFile.Size())
Output: 2048
Source Files
ΒΆ
Directories
ΒΆ
Path | Synopsis |
---|---|
example
|
|
middleware/basicauth/middl_v1
basic auth
|
basic auth |
middleware/cache/basic
Example of basic cache middleware usage in Quick
|
Example of basic cache middleware usage in Quick |
middleware/cache/custom-key
Example of cache middleware with custom key generation in Quick
|
Example of cache middleware with custom key generation in Quick |
middleware/cache/redis
Example of cache middleware with real Redis storage in Quick
|
Example of cache middleware with real Redis storage in Quick |
middleware/cache/redis.mock
Example of cache middleware with Redis storage in Quick
|
Example of cache middleware with Redis storage in Quick |
static/quick.embed
Embed.FS allows you to include files directly into the binary during compilation, eliminating the need to load files from the file system at runtime.
|
Embed.FS allows you to include files directly into the binary during compilation, eliminating the need to load files from the file system at runtime. |
upload.multipart/quick/file
Uploading multiple files using Quick is simple, and much more minimalistic than the patterns we've seen in other frameworks.
|
Uploading multiple files using Quick is simple, and much more minimalistic than the patterns we've seen in other frameworks. |
upload.multipart/quick/file.copy
Uploading multiple files using Quick is simple, and much more minimalistic than the patterns we've seen in other frameworks.
|
Uploading multiple files using Quick is simple, and much more minimalistic than the patterns we've seen in other frameworks. |
upload.multipart/quick/files
Uploading multiple files using Quick is simple, and much more minimalistic than the patterns we've seen in other frameworks.
|
Uploading multiple files using Quick is simple, and much more minimalistic than the patterns we've seen in other frameworks. |
Package gcolor provides a fluent and expressive API for styling terminal output using ANSI escape codes.
|
Package gcolor provides a fluent and expressive API for styling terminal output using ANSI escape codes. |
Basic usage:
|
Basic usage: |
http
|
|
client
Package client provides an advanced HTTP client for making HTTP requests.
|
Package client provides an advanced HTTP client for making HTTP requests. |
internal
|
|
middleware
|
|
cache
Package cache provides a middleware for the Quick web framework that implements an in-memory caching system for HTTP responses.
|
Package cache provides a middleware for the Quick web framework that implements an in-memory caching system for HTTP responses. |
compress
Package compress provides middleware for compressing HTTP responses using gzip.
|
Package compress provides middleware for compressing HTTP responses using gzip. |
cors
Package cors provides middleware for handling Cross-Origin Resource Sharing (CORS) in HTTP servers.
|
Package cors provides middleware for handling Cross-Origin Resource Sharing (CORS) in HTTP servers. |
healthcheck
Package healthcheck provides a middleware and endpoint for application health monitoring.
|
Package healthcheck provides a middleware and endpoint for application health monitoring. |
helmet
Package helmet provides middleware for the Quick framework that sets various HTTP headers to help secure your application.
|
Package helmet provides middleware for the Quick framework that sets various HTTP headers to help secure your application. |
limiter
Package limiter provides middleware for rate limiting HTTP requests in Quick.
|
Package limiter provides middleware for rate limiting HTTP requests in Quick. |
logger
Package logger provides a middleware for structured logging in Quick.
|
Package logger provides a middleware for structured logging in Quick. |
maxbody
Package maxbody provides middleware to enforce request body size limits.
|
Package maxbody provides middleware to enforce request body size limits. |
msgid
Package msgid provides middleware for automatically generating and assigning a unique Message ID (MsgID) to incoming HTTP requests.
|
Package msgid provides middleware for automatically generating and assigning a unique Message ID (MsgID) to incoming HTTP requests. |
msguuid
Package msguuid provides a middleware for assigning a UUID to incoming HTTP requests.
|
Package msguuid provides a middleware for assigning a UUID to incoming HTTP requests. |
pprof
Package pprof provides a Quick middleware that integrates Go's built-in net/http/pprof profiler for runtime analysis, performance debugging, and memory/cpu profiling.
|
Package pprof provides a Quick middleware that integrates Go's built-in net/http/pprof profiler for runtime analysis, performance debugging, and memory/cpu profiling. |
recover
Package recover provides a middleware for the Quick web framework that gracefully handles panics during request processing.
|
Package recover provides a middleware for the Quick web framework that gracefully handles panics during request processing. |
Package rand provides utility functions for generating random values using only the Go standard library.
|
Package rand provides utility functions for generating random values using only the Go standard library. |
html
Package html provides a powerful and extensible HTML template engine for the Quick web framework, built on top of Go's html/template.
|
Package html provides a powerful and extensible HTML template engine for the Quick web framework, built on top of Go's html/template. |
Package uuid generates and inspects UUIDs.
|
Package uuid generates and inspects UUIDs. |