Documentation
¶
Index ¶
- Constants
- type ApiHandler
- type DefaultContext
- func (d *DefaultContext) EncryptedPassword() string
- func (d *DefaultContext) GetId() string
- func (d *DefaultContext) GetRoles() []string
- func (d *DefaultContext) SetEncryptedPassword(encryptedPassword string)
- func (d *DefaultContext) SetRequesterId(requesterId string)
- func (d *DefaultContext) SetRoles(roles ...string)
- type Principal
- type Request
- func (ctx *Request[T]) BadRequest(message string)
- func (ctx *Request[T]) Created(body any)
- func (ctx *Request[T]) Done()
- func (ctx *Request[T]) Error(message string, status int)
- func (ctx *Request[T]) Flush()
- func (ctx *Request[T]) Forbidden(message string)
- func (ctx *Request[T]) FormFile(name string) (multipart.File, *multipart.FileHeader, error)
- func (ctx *Request[T]) FormValue(name string) any
- func (ctx *Request[T]) GetSample() SampleContext[T]
- func (ctx *Request[T]) GetSessionId() string
- func (ctx *Request[T]) HeaderOf(key string) string
- func (ctx *Request[T]) HeaderOfOrElse(key string, defaultHeader string) string
- func (ctx *Request[T]) HeadersOf(key string) []string
- func (ctx *Request[T]) HeadersOfOrElse(key string, defaultHeaders []string) []string
- func (ctx *Request[T]) InternalServerError(message string)
- func (ctx *Request[T]) InvalidInput()
- func (ctx *Request[T]) Next(next http.Handler)
- func (ctx *Request[T]) NoContent(body any)
- func (ctx *Request[T]) NotFount(body any)
- func (ctx *Request[T]) Ok(body any)
- func (ctx *Request[T]) ParseMultipartForm(maxMemory int64) error
- func (ctx *Request[T]) PathValueOf(key string) string
- func (ctx *Request[T]) QueriesOf(key string) []string
- func (ctx *Request[T]) QueriesOfElse(key string, defaultQueries []string) []string
- func (ctx *Request[T]) QueryOf(key string) string
- func (ctx *Request[T]) QueryOfOrElse(key string, defaultQuery string) string
- func (ctx *Request[T]) Response(body any, status int)
- func (ctx *Request[T]) Unauthorized()
- func (ctx *Request[T]) Write(body any, status int)
- func (ctx *Request[T]) WriteFile(file []byte, fileName string) error
- func (ctx *Request[T]) WriteReader(reader *bytes.Reader, fileName string) error
- type SampleContext
Constants ¶
const ( XApiKey = "X-Api-Key" Authorization = "Authorization" )
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 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 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 ¶
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 ¶
BadRequest sends an HTTP 400 Bad Request response with a given message.
func (*Request[T]) Created ¶
Created sends an HTTP 201 Created response with the provided body as the response payload.
func (*Request[T]) Error ¶
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]) FormFile ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
NoContent sends an HTTP 204 No Content response. The body is ignored as the status indicates no body.
func (*Request[T]) NotFount ¶
NotFount sends an HTTP 404 Not Found response with the provided body as the response payload.
func (*Request[T]) Ok ¶
Ok sends an HTTP 200 OK response with the provided body as the response payload.
func (*Request[T]) ParseMultipartForm ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.
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 }