Documentation ¶
Overview ¶
Note: This package requires Go version 1.20 or later.
For more information and usage examples, refer to the README and documentation at https://gitlab.com/fruitygo/pnutmux.
Index ¶
- Constants
- func CompileRegex(endpoint string, pairs ...string) (*regexp.Regexp, error)
- func Gzip(next http.HandlerFunc) http.HandlerFunc
- func NewHTTP2ServerWrapper(addr string, handler http.Handler, ...) (*serverwrapper, error)
- func NewRouter(semCount uint, logger contract.Logger, http2Config *HTTP2Config) contract.Router
- func NewRouterWithRedis(semCount uint, logger contract.Logger, rp *RateLimitingParams, ...) contract.Router
- func NewServerWrapper(addr string, handler http.Handler, ...) *serverwrapper
- func NewWrappedResponseWriter(l contract.Logger, rw http.ResponseWriter) *wrappedResponseWriter
- func QueryVar(ctx context.Context, key string) []string
- func QueryVars(ctx context.Context) map[string][]string
- func Respond(w http.ResponseWriter, data interface{}, code int, escapeHTML bool)
- func RespondErr(w http.ResponseWriter, code int)
- func ServeHTML(w http.ResponseWriter, htmlContent io.Reader, code int)
- func SetAllowedOrigin(origins string) error
- func Subpath() string
- func Var(ctx context.Context, key string) string
- func Vars(ctx context.Context) map[string]string
- type HTTP2Config
- type MiddlewareFunc
- type PnutRouter
- func (r *PnutRouter) Register(reg *regexp.Regexp, handler http.HandlerFunc, weight pnutconfig.RequestWeight, ...) error
- func (r *PnutRouter) Run(addr string, idleTimeout, readTimeout, writeTimeout time.Duration) error
- func (r *PnutRouter) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (r *PnutRouter) SetNotFoundHandler(handler http.HandlerFunc)
- func (r *PnutRouter) Stop() error
- type RateLimitingParams
Constants ¶
const ( IdPattern = `[0-9]+` // Matches any sequence of digits, used for IDs. NamePattern = `[a-zA-Z]+` // Matches any sequence of letters, used for names. WordPattern = `\w+` // Matches any sequence of word characters (letters, digits, underscores). WordCaseInsensitivePattern = `(?i)\w+` // Matches any sequence of word characters, case-insensitive. EmailPattern = `[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}` // Matches any valid email address. UrlPattern = `https?://\S+` // Matches any valid http or https URL. HexObjectIdPattern = `[a-fA-F0-9]+` // Matches any sequence of hexadecimal digits, used for object IDs. FirebaseUIDPattern = `[a-zA-Z0-9+/=]+` // Matches any valid Firebase user ID. MongoDBObjectIdPattern = `[0-9a-fA-F]{24}` // Matches any valid MongoDB ObjectID. FilePatternWithDot = `.*\.[^/]*$` // Matches any file path with a file extension. )
const ( // Unlimited represents an unlimited request weight. Unlimited pnutconfig.RequestWeight = 0 )
Variables ¶
This section is empty.
Functions ¶
func CompileRegex ¶ added in v1.1.7
CompileRegex compiles a regular expression pattern from a provided endpoint and key-value parameter pairs, returning the compiled pattern and any compilation errors.
To set a parameter as a subpath, use the key pnutmux.Subpath.
In order to create a endpoint at the root, use an empty string as the endpoint or use forward slash "/".
To define your pairs of key -> value parameters, provide them as a list of strings, where the first string is the key and the second string is the value. A check is performed to ensure that the number of parameters is even, since they are pairs of key -> values.
Do not include any regex anchors for the values, as they are added automatically. Adding them will lead to unexpected results.
Here is an example of how to use this function to create a regex pattern for a URL endpoint:
/jobs/{job_id}/applications/{application_id}
CompileRegex("/jobs", "job_id", pnutmux.IdPattern, "applications", pnutmux.Subpath, "application_id", pnutmux.IdPattern)
func Gzip ¶ added in v1.13.0
func Gzip(next http.HandlerFunc) http.HandlerFunc
Gzip returns an http.HandlerFunc that compresses the HTTP response using gzip compression.
It checks the "Accept-Encoding" header of the HTTP request to determine if the client supports gzip compression.
func NewHTTP2ServerWrapper ¶ added in v1.13.0
func NewHTTP2ServerWrapper(addr string, handler http.Handler, idleTimeout, readTimeout, writeTimeout time.Duration, http2Config *HTTP2Config) (*serverwrapper, error)
NewHTTP2ServerWrapper creates a new serverwrapper instance with http/2 enabled.
func NewRouter ¶
NewRouter creates and returns a new PnutRouter, implementing the contract.Router interface, with a specified semaphore count.
An optional contract.Logger can be provided to customize logging behavior, otherwise a default logger implementation is used.
A valid TLS configuration will enable HTTP2 if provided. If the HTTP2Config pointer is nil or struct contains zero values, HTTP2 will not be enabled.
func NewRouterWithRedis ¶ added in v1.13.0
func NewRouterWithRedis(semCount uint, logger contract.Logger, rp *RateLimitingParams, http2Config *HTTP2Config) contract.Router
NewRouterWithRedis creates and returns a new PnutRouter, implementing the contract.Router interface, with a specified semaphore count and optional Redis-Based rate limiting.
An optional contract.Logger can be provided to customize logging behavior, and a Redis client, timeout, and maximum daily calls can be provided for rate limiting.
If one of the parameters for rate limiting is not provided, the router will be created without rate limiting.
A valid TLS configuration will enable HTTP2 if provided. If the HTTP2Config pointer is nil or struct contains zero values, HTTP2 will not be enabled.
func NewServerWrapper ¶ added in v1.13.0
func NewServerWrapper(addr string, handler http.Handler, idleTimeout, readTimeout, writeTimeout time.Duration) *serverwrapper
NewServerWrapper creates a new serverwrapper instance.
func NewWrappedResponseWriter ¶ added in v1.13.0
func NewWrappedResponseWriter(l contract.Logger, rw http.ResponseWriter) *wrappedResponseWriter
NewWrappedResponseWriter creates a new instance of the wrappedResponseWriter struct.
func QueryVar ¶ added in v1.1.7
QueryVar retrieves the value of a specified query variable from a given context, returning an empty string if the context lacks the necessary information or the key is not found.
func QueryVars ¶ added in v1.1.7
QueryVars retrieves query variables from a given context, returning them as a map[string][]string or nil if the context lacks the necessary information.
func Respond ¶ added in v1.13.0
func Respond(w http.ResponseWriter, data interface{}, code int, escapeHTML bool)
Respond writes a JSON response to the provided http.ResponseWriter with the given data and HTTP status code.
It utilizes the apijuice.WriteJSONResponse function for writing the response.
The response is not compressed, use pnutmux.Gzip() middleware to enable compression.
Parameters:
- w: http.ResponseWriter to write the response to.
- data: Data to be serialized and sent as the response payload.
- code: HTTP status code to be set in the response.
func RespondErr ¶ added in v1.13.0
func RespondErr(w http.ResponseWriter, code int)
RespondError writes an error response to the provided http.ResponseWriter with the given error message and HTTP status code.
It utilizes the apijuice.WriteErrorResponse function for writing the error response.
The response message is extracted from the error code with http.StatusText.
Parameters:
- w: http.ResponseWriter to write the error response to.
- code: HTTP status code to be set in the response.
func ServeHTML ¶ added in v1.14.3
func ServeHTML(w http.ResponseWriter, htmlContent io.Reader, code int)
ServeHTML writes an HTML response to the provided http.ResponseWriter with the given HTML content and HTTP status code.
Parameters:
- w: http.ResponseWriter to write the response to.
- htmlContent: HTML content to be sent as the response payload.
- code: HTTP status code to be set in the response.
func SetAllowedOrigin ¶ added in v1.1.7
SetAllowedOrigins sets the ALLOWED_ORIGINS environment variable to a provided, comma-separated list of allowed origins for CORS, logging and returning any errors encountered.
func Subpath ¶ added in v1.1.7
func Subpath() string
Subpath returns a string representing a subpath. Currently, it returns the static string "subpath".
Types ¶
type HTTP2Config ¶ added in v1.13.0
type HTTP2Config struct { UseH2C bool // Use H2C if true, otherwise use HTTPS. FS embed.FS // File system for embedded files. Optional if UseH2C is true. CertificateFile string // Path to the certificate file. Optional if UseH2C is true. KeyFile string // Path to the key file. Optional if UseH2C is true. }
HTTP2Config contains TLS configuration information.
func (*HTTP2Config) IsValid ¶ added in v1.13.0
func (h *HTTP2Config) IsValid() bool
IsValid checks if the HTTP2Config struct is valid.
type MiddlewareFunc ¶ added in v1.1.7
type MiddlewareFunc func(http.HandlerFunc) http.HandlerFunc
MiddlewareFunc represents a middleware function. It takes an http.HandlerFunc as input and returns an http.HandlerFunc.
This type can be used to define middleware functions that can be chained together using the Chain function.
func Chain ¶ added in v1.1.7
func Chain(handlers ...MiddlewareFunc) MiddlewareFunc
Chain combines multiple MiddlewareFunc functions into a single MiddlewareFunc, creating a middleware chain. The returned MiddlewareFunc applies each input middleware function to the next one in reverse order.
The function takes a variadic number of MiddlewareFunc functions as input. The order of the input functions represents the order in which they will be applied in the middleware chain, with the first function being applied last.
The returned MiddlewareFunc can be used as a middleware in an HTTP server because it follows the http.HandlerFunc interface.
type PnutRouter ¶ added in v1.1.7
type PnutRouter struct {
// contains filtered or unexported fields
}
PnutRouter represents a router for handling HTTP requests. It uses a sync.RWMutex for synchronization, stores the registered routes in a map[*regexp.Regexp]route, and has an http.HandlerFunc for handling not found routes.
It holds the server instance in a contract.Server, uses a contract.Logger for logging, and a contract.Responder for responding.
func (*PnutRouter) Register ¶ added in v1.1.7
func (r *PnutRouter) Register(reg *regexp.Regexp, handler http.HandlerFunc, weight pnutconfig.RequestWeight, methods ...string) error
Register registers a handler function for the specified regular expression and HTTP methods on the PnutRouter.
If the router is not using Redis for rate limiting, the weight argument should be Unlimited, or 0.
func (*PnutRouter) Run ¶ added in v1.1.7
func (r *PnutRouter) Run(addr string, idleTimeout, readTimeout, writeTimeout time.Duration) error
Run starts the HTTP server on the PnutRouter, listening for incoming requests on the provided address.
Returns an error if the server is already running or encounters an error during execution.
func (*PnutRouter) ServeHTTP ¶ added in v1.1.7
func (r *PnutRouter) ServeHTTP(w http.ResponseWriter, req *http.Request)
ServeHTTP handles incoming HTTP requests, allowing PnutRouter to implement the http.Handler interface.
func (*PnutRouter) SetNotFoundHandler ¶ added in v1.1.7
func (r *PnutRouter) SetNotFoundHandler(handler http.HandlerFunc)
SetNotFoundHandler sets the custom not found handler for the PnutRouter.
func (*PnutRouter) Stop ¶ added in v1.1.7
func (r *PnutRouter) Stop() error
Stop gracefully stops the HTTP server on the PnutRouter, returning an error if there is an issue shutting down or if the server is not running.
type RateLimitingParams ¶ added in v1.13.0
type RateLimitingParams struct { RedisClient *redis.Client RedisTimeout time.Duration MaxDailyScore uint HeaderKey *string GroupID string }
RateLimitingParams represents the parameters for configuring rate limiting.
RedisClient is the Redis client to use for rate limiting.
RedisTimeout is the timeout to use for Redis operations.
MaxDailyScore is the maximum daily score to use for rate limiting.
HeaderKey is the header key to use for rate limiting based on a custom header value, using this value as the identifier of the request.
GroupID is the group ID to use to allow rate limiting of a user across multiple microservices.
All parameters are required for rate limiting to be enabled, except for HeaderKey, which can be nil to use the IP-Based rate limiting.
If any of the parameters are zero values, rate limiting will not be enabled.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
internal
|
|
adapter/util/logger
Package logger is a package that provides a logger interface and an adapter for the slog package.
|
Package logger is a package that provides a logger interface and an adapter for the slog package. |
adapter/util/responder
Package responder provides an adapter for writing responses to the response writer.
|
Package responder provides an adapter for writing responses to the response writer. |