http

package
v1.16.5 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2025 License: MIT Imports: 7 Imported by: 142

Documentation

Index

Constants

View Source
const (
	MethodHead       = http.MethodHead
	MethodGet        = http.MethodGet
	MethodPost       = http.MethodPost
	MethodPut        = http.MethodPut
	MethodDelete     = http.MethodDelete
	MethodPatch      = http.MethodPatch
	MethodOptions    = http.MethodOptions
	MethodConnect    = http.MethodConnect
	MethodTrace      = http.MethodTrace
	MethodAny        = "ANY"
	MethodResource   = "RESOURCE"
	MethodStatic     = "STATIC"
	MethodStaticFile = "STATIC_FILE"
	MethodStaticFS   = "STATIC_FS"
)
View Source
const (
	DefaultAbortStatus = http.StatusBadRequest

	StatusContinue           = http.StatusContinue
	StatusSwitchingProtocols = http.StatusSwitchingProtocols
	StatusProcessing         = http.StatusProcessing
	StatusEarlyHints         = http.StatusEarlyHints

	StatusOK                   = http.StatusOK
	StatusCreated              = http.StatusCreated
	StatusAccepted             = http.StatusAccepted
	StatusNonAuthoritativeInfo = http.StatusNonAuthoritativeInfo
	StatusNoContent            = http.StatusNoContent
	StatusResetContent         = http.StatusResetContent
	StatusPartialContent       = http.StatusPartialContent
	StatusMultiStatus          = http.StatusMultiStatus
	StatusAlreadyReported      = http.StatusAlreadyReported
	StatusIMUsed               = http.StatusIMUsed

	StatusMultipleChoices   = http.StatusMultipleChoices
	StatusMovedPermanently  = http.StatusMovedPermanently
	StatusFound             = http.StatusFound
	StatusSeeOther          = http.StatusSeeOther
	StatusNotModified       = http.StatusNotModified
	StatusUseProxy          = http.StatusUseProxy
	StatusTemporaryRedirect = http.StatusTemporaryRedirect
	StatusPermanentRedirect = http.StatusPermanentRedirect

	StatusBadRequest                   = http.StatusBadRequest
	StatusUnauthorized                 = http.StatusUnauthorized
	StatusPaymentRequired              = http.StatusPaymentRequired
	StatusForbidden                    = http.StatusForbidden
	StatusNotFound                     = http.StatusNotFound
	StatusMethodNotAllowed             = http.StatusMethodNotAllowed
	StatusNotAcceptable                = http.StatusNotAcceptable
	StatusProxyAuthRequired            = http.StatusProxyAuthRequired
	StatusRequestTimeout               = http.StatusRequestTimeout
	StatusConflict                     = http.StatusConflict
	StatusGone                         = http.StatusGone
	StatusLengthRequired               = http.StatusLengthRequired
	StatusPreconditionFailed           = http.StatusPreconditionFailed
	StatusRequestEntityTooLarge        = http.StatusRequestEntityTooLarge
	StatusRequestURITooLong            = http.StatusRequestURITooLong
	StatusUnsupportedMediaType         = http.StatusUnsupportedMediaType
	StatusRequestedRangeNotSatisfiable = http.StatusRequestedRangeNotSatisfiable
	StatusExpectationFailed            = http.StatusExpectationFailed
	StatusTeapot                       = http.StatusTeapot
	StatusMisdirectedRequest           = http.StatusMisdirectedRequest
	StatusUnprocessableEntity          = http.StatusUnprocessableEntity
	StatusLocked                       = http.StatusLocked
	StatusFailedDependency             = http.StatusFailedDependency
	StatusTooEarly                     = http.StatusTooEarly
	StatusUpgradeRequired              = http.StatusUpgradeRequired
	StatusPreconditionRequired         = http.StatusPreconditionRequired
	StatusTooManyRequests              = http.StatusTooManyRequests
	StatusRequestHeaderFieldsTooLarge  = http.StatusRequestHeaderFieldsTooLarge
	StatusUnavailableForLegalReasons   = http.StatusUnavailableForLegalReasons

	StatusInternalServerError           = http.StatusInternalServerError
	StatusNotImplemented                = http.StatusNotImplemented
	StatusBadGateway                    = http.StatusBadGateway
	StatusServiceUnavailable            = http.StatusServiceUnavailable
	StatusGatewayTimeout                = http.StatusGatewayTimeout
	StatusHTTPVersionNotSupported       = http.StatusHTTPVersionNotSupported
	StatusVariantAlsoNegotiates         = http.StatusVariantAlsoNegotiates
	StatusInsufficientStorage           = http.StatusInsufficientStorage
	StatusLoopDetected                  = http.StatusLoopDetected
	StatusNotExtended                   = http.StatusNotExtended
	StatusNetworkAuthenticationRequired = http.StatusNetworkAuthenticationRequired
)

Variables

This section is empty.

Functions

func StatusText added in v1.10.0

func StatusText(code int) string

StatusText returns a text for the HTTP status code. It returns the empty string if the code is unknown.

Types

type AbortableResponse added in v1.15.0

type AbortableResponse interface {
	Response
	Abort() error
}

type Context added in v1.0.1

type Context interface {
	context.Context
	// Context returns the Context
	Context() context.Context
	// WithContext adds a new context to an existing one
	WithContext(ctx context.Context)
	// WithValue add value associated with key in context
	WithValue(key any, value any)
	// Request returns the ContextRequest
	Request() ContextRequest
	// Response returns the ContextResponse
	Response() ContextResponse
}

type ContextRequest added in v1.13.1

type ContextRequest interface {
	// Cookie retrieves the value of the specified cookie by its key.
	Cookie(key string, defaultValue ...string) string
	// Header retrieves the value of the specified HTTP header by its key.
	// If the header is not found, it returns the optional default value (if provided).
	Header(key string, defaultValue ...string) string
	// Headers return all the HTTP headers of the request.
	Headers() http.Header
	// Method retrieves the HTTP request method (e.g., GET, POST, PUT).
	Method() string
	// Name retrieves the name of the route for the request.
	Name() string
	// OriginPath retrieves the original path of the request: /users/{id}
	OriginPath() string
	// Path retrieves the current path information for the request: /users/1
	Path() string
	// Url retrieves the URL (excluding the query string) for the request.
	Url() string
	// FullUrl retrieves the full URL, including the query string, for the request.
	FullUrl() string
	// Info retrieves the route information for the request.
	Info() Info
	// Ip retrieves the client's IP address.
	Ip() string
	// Host retrieves the host name.
	Host() string
	// All retrieves data from JSON, form, and query parameters.
	All() map[string]any
	// Bind retrieve json and bind to obj
	Bind(obj any) error
	// BindQuery bind query parameters to obj
	BindQuery(obj any) error
	// Route retrieves a route parameter from the request path (e.g., /users/{id}).
	Route(key string) string
	// RouteInt retrieves a route parameter from the request path and attempts to parse it as an integer.
	RouteInt(key string) int
	// RouteInt64 retrieves a route parameter from the request path and attempts to parse it as a 64-bit integer.
	RouteInt64(key string) int64
	// Query retrieves a query string parameter from the request (e.g., /users?id=1).
	Query(key string, defaultValue ...string) string
	// QueryInt retrieves a query string parameter from the request and attempts to parse it as an integer.
	QueryInt(key string, defaultValue ...int) int
	// QueryInt64 retrieves a query string parameter from the request and attempts to parse it as a 64-bit integer.
	QueryInt64(key string, defaultValue ...int64) int64
	// QueryBool retrieves a query string parameter from the request and attempts to parse it as a boolean.
	QueryBool(key string, defaultValue ...bool) bool
	// QueryArray retrieves a query string parameter from the request and returns it as a slice of strings.
	QueryArray(key string) []string
	// QueryMap retrieves a query string parameter from the request and returns it as a map of key-value pairs.
	QueryMap(key string) map[string]string
	// Queries returns all the query string parameters from the request as a map of key-value pairs.
	Queries() map[string]string

	// HasSession checks if the request has a session.
	HasSession() bool
	// Session retrieves the session associated with the request.
	Session() session.Session
	// SetSession sets the session associated with the request.
	SetSession(session session.Session) ContextRequest

	// Input retrieves data from the request in the following order: JSON, form, query, and route parameters.
	Input(key string, defaultValue ...string) string
	InputArray(key string, defaultValue ...[]string) []string
	InputMap(key string, defaultValue ...map[string]any) map[string]any
	InputMapArray(key string, defaultValue ...[]map[string]any) []map[string]any
	InputInt(key string, defaultValue ...int) int
	InputInt64(key string, defaultValue ...int64) int64
	InputBool(key string, defaultValue ...bool) bool
	// File retrieves a file by its key from the request.
	File(name string) (filesystem.File, error)
	Files(name string) ([]filesystem.File, error)

	// Abort aborts the request with the specified HTTP status code, default is 400.
	Abort(code ...int)
	// AbortWithStatus aborts the request with the specified HTTP status code.
	// DEPRECATED: Use Abort instead.
	AbortWithStatus(code int)
	// AbortWithStatusJson aborts the request with the specified HTTP status code
	// and returns a JSON response object.
	// DEPRECATED: Use Response().Json().Abort() instead.
	AbortWithStatusJson(code int, jsonObj any)
	// Next skips the current request handler, allowing the next middleware or handler to be executed.
	Next()
	// Origin retrieves the underlying *http.Request object for advanced request handling.
	Origin() *http.Request

	// Validate performs request data validation using specified rules and options.
	Validate(rules map[string]string, options ...validation.Option) (validation.Validator, error)
	// ValidateRequest validates the request data against a pre-defined FormRequest structure
	// and returns validation errors, if any.
	ValidateRequest(request FormRequest) (validation.Errors, error)
}

type ContextResponse added in v1.13.1

type ContextResponse interface {
	// Cookie adds a cookie to the response.
	Cookie(cookie Cookie) ContextResponse
	// Data write the given data to the response.
	Data(code int, contentType string, data []byte) AbortableResponse
	// Download initiates a file download by specifying the file path and the desired filename
	Download(filepath, filename string) Response
	// File serves a file located at the specified file path as the response.
	File(filepath string) Response
	// Header sets an HTTP header field with the given key and value.
	Header(key, value string) ContextResponse
	// Json sends a JSON response with the specified status code and data object.
	Json(code int, obj any) AbortableResponse
	// NoContent sends a response with no-body and the specified status code.
	NoContent(code ...int) AbortableResponse
	// Origin returns the ResponseOrigin
	Origin() ResponseOrigin
	// Redirect performs an HTTP redirect to the specified location with the given status code.
	Redirect(code int, location string) AbortableResponse
	// String writes a string response with the specified status code and format.
	// The 'values' parameter can be used to replace placeholders in the format string.
	String(code int, format string, values ...any) AbortableResponse
	// Success returns ResponseStatus with a 200 status code.
	Success() ResponseStatus
	// Status sets the HTTP response status code and returns the ResponseStatus.
	Status(code int) ResponseStatus
	// Stream sends a streaming response with the specified status code and the given reader.
	Stream(code int, step func(w StreamWriter) error) Response
	// View returns ResponseView
	View() ResponseView
	// Writer returns the underlying http.ResponseWriter associated with the response.
	Writer() http.ResponseWriter
	// WithoutCookie removes a cookie from the response.
	WithoutCookie(name string) ContextResponse
	// Flush flushes any buffered data to the client.
	Flush()
}
type Cookie struct {

	// Expires specifies the maximum age of the cookie.It is considered
	// expired if the current time is after the Expires value.
	Expires time.Time

	// Name is the name of the cookie.
	Name string

	// Value is the value associated with the cookie's name.
	Value string

	// Path specifies the subset of URLs to which this cookie applies.
	Path string

	// Domain specifies the domain for which the cookie is valid.
	Domain string

	// Raw is the unparsed value of the "Set-Cookie" header received from
	// the server.
	Raw string

	// SameSite allows a server to define a cookie attribute, making it
	// impossible for the browser to send this cookie along with cross-site
	// requests.It helps mitigate the risk of cross-origin information leaks.
	SameSite string

	// MaxAge specifies the maximum age of the cookie in seconds.A zero or
	// negative MaxAge means that the cookie is not persistent and will be
	// deleted when the browser is closed.
	MaxAge int

	// Secure indicates whether the cookie should only be sent over secure
	// (HTTPS) connections.
	Secure bool

	// HttpOnly indicates whether the cookie is accessible only through
	// HTTP requests, and not through JavaScript.
	HttpOnly bool
}

Cookie represents an HTTP cookie as defined by RFC 6265.

type FormRequest

type FormRequest interface {
	// Authorize determine if the user is authorized to make this request.
	Authorize(ctx Context) error
	// Rules get the validation rules that apply to the request.
	Rules(ctx Context) map[string]string
}

type FormRequestWithAttributes added in v1.15.0

type FormRequestWithAttributes interface {
	// Attributes get custom attributes for validator errors.
	Attributes(ctx Context) map[string]string
}

type FormRequestWithFilters added in v1.15.0

type FormRequestWithFilters interface {
	// Filters get the custom filters that apply to the request.
	Filters(ctx Context) map[string]string
}

type FormRequestWithMessages added in v1.15.0

type FormRequestWithMessages interface {
	// Messages get the validation messages that apply to the request.
	Messages(ctx Context) map[string]string
}

type FormRequestWithPrepareForValidation added in v1.15.0

type FormRequestWithPrepareForValidation interface {
	// PrepareForValidation prepare the data for validation.
	PrepareForValidation(ctx Context, data validation.Data) error
}

type HandlerFunc added in v1.0.0

type HandlerFunc func(Context) Response

type Info added in v1.15.12

type Info struct {
	Handler string `json:"handler"`
	Method  string `json:"method"`
	Name    string `json:"name"`
	Path    string `json:"path"`
}

type Json added in v1.0.0

type Json map[string]any

type Limit added in v1.10.0

type Limit interface {
	// By set the signature key name for the rate limiter.
	By(key string) Limit
	// Response set the response callback that should be used.
	Response(func(ctx Context)) Limit
}

type Middleware added in v1.0.0

type Middleware func(Context)

type RateLimiter added in v1.10.0

type RateLimiter interface {
	// For register a new rate limiter.
	For(name string, callback func(ctx Context) Limit)
	// ForWithLimits register a new rate limiter with limits.
	ForWithLimits(name string, callback func(ctx Context) []Limit)
	// Limiter get a rate limiter instance by name.
	Limiter(name string) func(ctx Context) []Limit
}

type ResourceController added in v1.11.1

type ResourceController interface {
	// Index method for controller
	Index(Context) Response
	// Show method for controller
	Show(Context) Response
	// Store method for controller
	Store(Context) Response
	// Update method for controller
	Update(Context) Response
	// Destroy method for controller
	Destroy(Context) Response
}

type Response

type Response interface {
	Render() error
}

type ResponseOrigin added in v1.8.0

type ResponseOrigin interface {
	// Body returns the response's body content as a *bytes.Buffer.
	Body() *bytes.Buffer
	// Header returns the response's HTTP header.
	Header() http.Header
	// Size returns the size, in bytes, of the response's body content.
	Size() int
	// Status returns the HTTP status code of the response.
	Status() int
}

type ResponseStatus added in v1.12.5

type ResponseStatus interface {
	// Data write the given data to the Response.
	Data(contentType string, data []byte) AbortableResponse
	// Json sends a JSON AbortResponse with the specified data object.
	Json(obj any) AbortableResponse
	// String writes a string AbortResponse with the specified format and values.
	String(format string, values ...any) AbortableResponse
	// Stream sends a streaming response with the specified status code and the given reader.
	Stream(step func(w StreamWriter) error) Response
}

type ResponseView added in v1.13.1

type ResponseView interface {
	// Make generates a Response for the specified view with optional data.
	Make(view string, data ...any) Response
	// First generates a response for the first available view from the provided list.
	First(views []string, data ...any) Response
}

type Store added in v1.15.5

type Store interface {
	// Take takes a token from the given key if available, returning:
	//
	// - the configured limit size
	// - the number of remaining tokens in the interval
	// - the server time when new tokens will be available
	// - whether the take was successful
	// - any errors that occurred while performing the take - these should be
	//   backend errors (e.g. connection failures); Take() should never return an
	//   error for a bucket.
	//
	// If "ok" is false, the take was unsuccessful and the caller should NOT
	// service the request.
	//
	// See the note about keys on the interface documentation.
	Take(ctx context.Context, key string) (tokens, remaining, reset uint64, ok bool, err error)

	// Get gets the current limit and remaining tokens for the provided key. It
	// does not change any of the values.
	Get(ctx context.Context, key string) (tokens, remaining uint64, err error)

	// Set configures the limit at the provided key. If a limit already exists, it
	// is overwritten. This also sets the number of tokens in the bucket to the
	// limit.
	Set(ctx context.Context, key string, tokens uint64, interval time.Duration) error

	// Burst adds more tokens to the key's current bucket until the next interval
	// tick. This will allow the current bucket tick to exceed the maximum number
	// maximum ticks until the next interval.
	Burst(ctx context.Context, key string, tokens uint64) error
}

Store is an interface for limiter storage backends.

Keys should be hash, sanitized, or otherwise scrubbed of identifiable information they will be given to the store in plaintext. If you're rate limiting by IP address, for example, the IP address would be stored in the storage system in plaintext. This may be undesirable in certain situations, like when the store is a public database. In those cases, you should hash or HMAC the key before passing giving it to the store. If you want to encrypt the value, you must use homomorphic encryption to ensure the value always encrypts to the same ciphertext.

type StreamWriter added in v1.15.0

type StreamWriter interface {
	// Write writes the specified data to the response.
	Write(data []byte) (int, error)

	// WriteString writes the specified string to the response.
	WriteString(data string) (int, error)

	// Flush flushes any buffered data to the client.
	Flush() error
}

type View added in v1.13.1

type View interface {
	// Exists checks if a view with the specified name exists.
	Exists(view string) bool
	// Share associates a key-value pair, where the key is a string and the value is of any type,
	// with the current view context. This shared data can be accessed by other parts of the application.
	Share(key string, value any)
	// Shared retrieves the value associated with the given key from the current view context's shared data.
	// If the key does not exist, it returns the optional default value (if provided).
	Shared(key string, def ...any) any
	// GetShared returns a map containing all the shared data associated with the current view context.
	GetShared() map[string]any
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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