context

package
v1.0.8 Latest Latest
Warning

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

Go to latest
Published: May 26, 2025 License: Apache-2.0 Imports: 11 Imported by: 3

Documentation

Index

Constants

View Source
const (
	XApiKey       = "X-Api-Key"
	Authorization = "Authorization"
)
View Source
const (
	ContentType               = "Content-Type"
	ApplicationJson           = "application/json"
	TextPlain                 = "text/plain"
	TextHtml                  = "text/html"
	TextXml                   = "text/xml"
	MultipartFormData         = "multipart/form-data"
	ApplicationFormUrlEncoded = "application/x-www-form-urlencoded"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type ApiHandler

type ApiHandler[T Principal] interface {
	Handler(ctx *Request[T], err error, source string)
}

type DefaultContext

type DefaultContext struct {
	// contains filtered or unexported fields
}

DefaultContext is a simple implementation of a context that holds roles, an encrypted password, and an optional requester ID. This struct is intended for use in **test and development environments only** and is **not recommended for production use**.

In production environments, you should use a more secure and robust implementation that:

  • Properly manages sensitive data (e.g., passwords).
  • Validates and sanitizes input.
  • Integrates with your authentication and authorization systems.

Fields:

  • roles: A slice of strings representing the roles associated with this context.
  • encryptedPassword: A string representing the encrypted password. Note that this is not secure for production use. -requesterId: A pointer to a string representing an optional requester ID. If not provided, the default requester ID is used.

func NewDefaultCtx

func NewDefaultCtx() *DefaultContext

NewDefaultCtx creates and returns a new instance of DefaultContext. This is a convenience function for initializing the context in test/development environments.

func (*DefaultContext) EncryptedPassword

func (d *DefaultContext) EncryptedPassword() string

EncryptedPassword returns the encrypted password stored in the context. WARNING: This method does not decrypt the password. It simply returns the stored value.

func (*DefaultContext) GetId

func (d *DefaultContext) GetId() string

GetId returns the requester ID associated with the context. If no custom requester ID is set, it returns the default requester ID. WARNING: The default requester ID is hardcoded and is **not secure for production use**. In production, you should use a unique and secure requester ID for each request.

func (*DefaultContext) GetRoles

func (d *DefaultContext) GetRoles() []string

GetRoles returns the roles associated with the context. This is useful for role-based access control (RBAC).

func (*DefaultContext) SetEncryptedPassword

func (d *DefaultContext) SetEncryptedPassword(encryptedPassword string)

SetEncryptedPassword sets the encrypted password in the context. WARNING: This method does not perform any encryption or validation. In production, you should use a secure encryption mechanism (e.g., bcrypt, Argon2).

func (*DefaultContext) SetRequesterId

func (d *DefaultContext) SetRequesterId(requesterId string)

SetRequesterId sets the default requester ID for the context by assigning the provided string pointer torequesterId.

func (*DefaultContext) SetRoles

func (d *DefaultContext) SetRoles(roles ...string)

SetRoles sets the roles associated with the context. If no roles are provided, it initializes the roles slice as empty. This is useful for simulating role-based access control in test/development environments.

type Principal

type Principal interface {
	GetId() string
	GetRoles() []string
	EncryptedPassword() string
}

type Request

type Request[T Principal] struct {
	Writer        *http.ResponseWriter
	Request       *http.Request
	ApiKey        string // The API key extracted from the HTTP request header. This is used to identify and authenticate the client making the API request.
	ApiKeyId      string // The unique identifier associated with the API key used in the request. Helps in tracking and logging API key usage.
	Authorization string // The bearer token or other authorization token extracted from the HTTP request header. Used to authenticate the user of the API.
	Principal     *T     // The principal context containing user or session-specific data, representing the authenticated entity in the request.

	AuthorizationClaims map[string]interface{} // A set of claims derived from the authorization token, providing additional metadata about the requester (e.g., roles, permissions, expiration).
	ApiKeyClaims        map[string]interface{} // A set of claims derived from the API key, detailing metadata associated with the key (e.g., usage limits, allowed resources).
	AccessId            string                 // A unique identifier representing access to a specific resource or API, often used for auditing or tracking access patterns.
	PathValues          map[string]string      // A map of route variables extracted from the request URL. Useful for handling dynamic URL parameters in the API endpoints.
	Headers             map[string][]string    // Headers contains a mapping of header keys to their respective values from the incoming HTTP request.
	QueryValues         map[string][]string    // A map containing the query parameters from the request URL. Each key corresponds to a query parameter name, and the value is a slice of strings representing the values of that parameter. Useful for processing and validating query parameters in API endpoints.
	Completed           bool                   // Completed indicates whether the task or process has been finished successfully or not.
	// contains filtered or unexported fields
}

func Of

func Of[T Principal](w http.ResponseWriter, r *http.Request, reference string) *Request[T]

Of retrieves the Request object from the request's context if it already exists. If no such object exists, it creates a new instance of Request with the given writer, request, and reference for logging or tracing purposes.

This function enhances the context of the current HTTP request with additional API-related information, such as API key, authorization token, and a unique session ID. The new context or the retrieved existing context is linked to the request to facilitate data sharing throughout the request's lifecycle.

Type Parameters:

  • T: A type that implements the Principal interface, which facilitates the storage and management of additional API-related data for the request.

Parameters:

  • w: The http.ResponseWriter used to construct the response for the client.
  • r: The *http.Request representing the HTTP request from the client.
  • reference: A string value for logging or reference purposes.

Returns:

  • A pointer to the Request of type T, which contains relevant API-related data.

Example usage:

ctx := Of[MyContextData](w, r, "MyReference")
ctx.GetSessionId() // Access session id

func (*Request[T]) BadRequest

func (ctx *Request[T]) BadRequest(message string)

BadRequest sends an HTTP 400 Bad Request response with a given message.

func (*Request[T]) Created

func (ctx *Request[T]) Created(body any)

Created sends an HTTP 201 Created response with the provided body as the response payload.

func (*Request[T]) Done

func (ctx *Request[T]) Done()

func (*Request[T]) Error

func (ctx *Request[T]) Error(message string, status int)

Error sends an HTTP error response with a status and a message. The response includes the timestamp and status code for debugging or informational purposes.

func (*Request[T]) Flush

func (ctx *Request[T]) Flush()

Flush clears all the fields in the Request, effectively resetting the context to its default state. This can be useful to prevent accidental reuse of sensitive data or to prepare for cleanup at the end of a request.

This function clears sensitive information such as API key, authorization tokens, claims, and other metadata. It also nils out the Writer and Request pointers to avoid accidental usage after the flush.

Usage Example:

ctx := Of[MyPrincipalContext](w, r, "ExampleReference")
// Process request here...
ctx.Flush() // Reset the context to its default state for cleanup.

func (*Request[T]) Forbidden

func (ctx *Request[T]) Forbidden(message string)

Forbidden sends an HTTP 403 Forbidden response with a given message.

func (*Request[T]) FormFile

func (ctx *Request[T]) FormFile(name string) (multipart.File, *multipart.FileHeader, error)

FormFile retrieves a file and its header from a multipart form with the given field name. The file is immediately closed after being read to avoid resource leaks.

Parameters:

  • name: The name of the form field containing the file to retrieve.

Returns:

  • multipart.File: The file object, or nil if an error occurs.
  • *multipart.FileHeader: The file header, or nil if an error occurs.
  • error: An error, if one occurs while retrieving the file.

Make sure to close the file when no need it anymore.

func (*Request[T]) FormValue

func (ctx *Request[T]) FormValue(name string) any

FormValue retrieves the first value for the given form field name from the parsed form data. If the form field does not exist, it returns an empty string.

Parameters:

  • name: The name of the form field to retrieve.

Returns:

  • The value of the form field or an empty string if it does not exist.

func (*Request[T]) GetSample

func (ctx *Request[T]) GetSample() SampleContext[T]

func (*Request[T]) GetSessionId

func (ctx *Request[T]) GetSessionId() string

GetSessionId retrieves the unique identifier for the current API session. This session ID is used for tracking the lifecycle of requests in a session.

func (*Request[T]) HeaderOf

func (ctx *Request[T]) HeaderOf(key string) string

HeaderOf retrieves the first value of the specified HTTP header from the request. If the header does not exist or has no values, an empty string is returned.

Parameters:

  • key: The name of the HTTP header to retrieve.

Returns:

  • The first value of the header or an empty string if it does not exist.

func (*Request[T]) HeaderOfOrElse

func (ctx *Request[T]) HeaderOfOrElse(key string, defaultHeader string) string

HeaderOfOrElse retrieves the first value of the specified HTTP header from the request. If the header does not exist or has no values, the provided default value is returned.

Parameters:

  • key: The name of the HTTP header to retrieve.
  • defaultHeader: The default value to return if the header does not exist.

Returns:

  • The first value of the header or the default value.

func (*Request[T]) HeadersOf

func (ctx *Request[T]) HeadersOf(key string) []string

HeadersOf retrieves all values of the specified HTTP header from the request. If the header does not exist, an empty slice is returned.

Parameters:

  • key: The name of the HTTP header to retrieve.

Returns:

  • A slice of strings containing all values of the header or an empty slice if it does not exist.

func (*Request[T]) HeadersOfOrElse

func (ctx *Request[T]) HeadersOfOrElse(key string, defaultHeaders []string) []string

HeadersOfOrElse retrieves all values of the specified HTTP header from the request. If the header does not exist, the provided default values are returned.

Parameters:

  • key: The name of the HTTP header to retrieve.
  • defaultHeaders: The default values to return if the header does not exist.

Returns:

  • A slice of strings containing all values of the header or the default values.

func (*Request[T]) InternalServerError

func (ctx *Request[T]) InternalServerError(message string)

InternalServerError sends an HTTP 500 Internal Server Error response with a given message.

func (*Request[T]) InvalidInput

func (ctx *Request[T]) InvalidInput()

InvalidInput sends an HTTP 400 Bad Request response with a standardized "Invalid input" message.

func (*Request[T]) Next

func (ctx *Request[T]) Next(next http.Handler)

Next forwards the request to the next HTTP handler in the middleware chain. It ensures the current Request is preserved during the request processing.

func (*Request[T]) NoContent

func (ctx *Request[T]) NoContent(body any)

NoContent sends an HTTP 204 No Content response. The body is ignored as the status indicates no body.

func (*Request[T]) NotFount

func (ctx *Request[T]) NotFount(body any)

NotFount sends an HTTP 404 Not Found response with the provided body as the response payload.

func (*Request[T]) Ok

func (ctx *Request[T]) Ok(body any)

Ok sends an HTTP 200 OK response with the provided body as the response payload.

func (*Request[T]) ParseMultipartForm

func (ctx *Request[T]) ParseMultipartForm(maxMemory int64) error

ParseMultipartForm parses the multipart form in the request body, storing up to maxMemory bytes of its file parts in memory, with the remainder stored on disk. This is necessary to access file uploads sent in a multipart request.

Parameters:

  • maxMemory: The maximum number of bytes to store in memory.

Returns:

  • error: An error if parsing fails.

func (*Request[T]) PathValueOf

func (ctx *Request[T]) PathValueOf(key string) string

PathValueOf retrieves the value of the specified path variable from the request URL. Path variables are extracted from dynamic segments of the route defined in the router.

Parameters:

  • key: The name of the path variable to retrieve.

Returns:

  • The value of the path variable or an empty string if it does not exist.

func (*Request[T]) QueriesOf

func (ctx *Request[T]) QueriesOf(key string) []string

QueriesOf retrieves all values of the specified query parameter from the request URL. If the query parameter does not exist, an empty slice is returned.

Parameters:

  • key: The name of the query parameter to retrieve.

Returns:

  • A slice of strings containing all values of the query parameter or an empty slice if it does not exist.

func (*Request[T]) QueriesOfElse

func (ctx *Request[T]) QueriesOfElse(key string, defaultQueries []string) []string

QueriesOfElse retrieves all values of the specified query parameter from the request URL. If the query parameter does not exist, the provided default values are returned.

Parameters:

  • key: The name of the query parameter to retrieve.
  • defaultQueries: The default values to return if the query parameter does not exist.

Returns:

  • A slice of strings containing all values of the query parameter or the default values.

func (*Request[T]) QueryOf

func (ctx *Request[T]) QueryOf(key string) string

QueryOf retrieves the first value of the specified query parameter from the request URL. If the query parameter does not exist or has no values, an empty string is returned.

Parameters:

  • key: The name of the query parameter to retrieve.

Returns:

  • The first value of the query parameter or an empty string if it does not exist.

func (*Request[T]) QueryOfOrElse

func (ctx *Request[T]) QueryOfOrElse(key string, defaultQuery string) string

QueryOfOrElse retrieves the first value of the specified query parameter from the request URL. If the query parameter does not exist or has no values, the provided default value is returned.

Parameters:

  • key: The name of the query parameter to retrieve.
  • defaultQuery: The default value to return if the query parameter does not exist.

Returns:

  • The first value of the query parameter or the default value.

func (*Request[T]) Response

func (ctx *Request[T]) Response(body any, status int)

Response sends a generic HTTP response with a given body and status code. It serializes the body to JSON and writes it to the response writer.

func (*Request[T]) Unauthorized

func (ctx *Request[T]) Unauthorized()

Unauthorized sends an HTTP 401 Unauthorized response with a standardized message.

func (*Request[T]) Write

func (ctx *Request[T]) Write(body any, status int)

func (*Request[T]) WriteFile

func (ctx *Request[T]) WriteFile(file []byte, fileName string) error

WriteFile streams a file as a response for download, using a given file name. Sets appropriate headers for file attachment and streams the content.

func (*Request[T]) WriteReader

func (ctx *Request[T]) WriteReader(reader *bytes.Reader, fileName string) error

WriteReader streams a file-like reader as a response for download with a given file name. Sets appropriate headers for file attachment and streams the reader's content.

type SampleContext

type SampleContext[T Principal] struct {
	ApiKey        string // The API key extracted from the HTTP request header. This is used to identify and authenticate the client making the API request.
	ApiKeyId      string // The unique identifier associated with the API key used in the request. Helps in tracking and logging API key usage.
	Authorization string // The bearer token or other authorization token extracted from the HTTP request header. Used to authenticate the user of the API.
	Principal     *T     // The principal context containing user or session-specific data, representing the authenticated entity in the request.

	AuthorizationClaims map[string]interface{} // A set of claims derived from the authorization token, providing additional metadata about the requester (e.g., roles, permissions, expiration).
	ApiKeyClaims        map[string]interface{} // A set of claims derived from the API key, detailing metadata associated with the key (e.g., usage limits, allowed resources).
	AccessId            string                 // A unique identifier representing access to a specific resource or API, often used for auditing or tracking access patterns.
	PathValues          map[string]string      // A map of route variables extracted from the request URL. Useful for handling dynamic URL parameters in the API endpoints.
	Headers             map[string][]string    // Headers contains a mapping of header keys to their respective values from the incoming HTTP request.
	QueryValues         map[string][]string    // A map containing the query parameters from the request URL. Each key corresponds to a query parameter name, and the value is a slice of strings representing the values of that parameter. Useful for processing and validating query parameters in API endpoints.
	// contains filtered or unexported fields
}

Jump to

Keyboard shortcuts

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