Documentation ¶
Overview ¶
Package middleware provides set of middleware functions that can be used to authenticate and authorize requests in HTTP server.It also supports handling CORS, propagating headers, integrating with New Relic APM, and enabling distributed tracing using OpenTelemetry.
Index ¶
- Constants
- Variables
- func AllowedCORSHeader() []string
- func CORS(envHeaders map[string]string) func(inner http.Handler) http.Handler
- func ErrorResponse(w http.ResponseWriter, r *http.Request, logger logger, ...)
- func ExemptPath(r *http.Request) bool
- func FetchErrResponseWithCode(statusCode int, reason, code string) *errors.MultipleErrors
- func GetDescription(err error) (description string, statusCode int)
- func GetIPAddress(r *http.Request) string
- func LDAP(logger log.Logger, options *LDAPOptions) func(inner http.Handler) http.Handler
- func Logging(logger logger, omitHeaders string) func(inner http.Handler) http.Handler
- func NewRelic(appname, license string) func(http.Handler) http.Handler
- func PrometheusMiddleware(next http.Handler) http.Handler
- func PropagateHeaders(inner http.Handler) http.Handler
- func PushDeprecatedFeature(featureName string)
- func PushSystemStats()
- func Recover(logger logger) func(inner http.Handler) http.Handler
- func Trace(appName, appVersion, tracerExporter string) func(inner http.Handler) http.Handler
- func ValidateHeaders(envHeaders string, logger logger) func(inner http.Handler) http.Handler
- type CacheEntry
- type Error
- type Header
- type LDAPOptions
- type Ldap
- type LdapCache
- type LogDataKey
- type LogLine
- type MethodGroup
- type StatusResponseWriter
Constants ¶
const ( ErrInvalidToken = Error("invalid_token") ErrInvalidRequest = Error("invalid_request") ErrServiceDown = Error("service_unavailable") ErrInvalidHeader = Error("invalid_header") ErrMissingHeader = Error("missing_header") ErrUnauthenticated = Error("failed_auth") ErrInvalidAppKey = Error("app_key_should_be_more_than_12_bytes") )
const ( ClientIPKey clientIP = "clientIP" AuthenticatedUserIDKey authenticatedUserID = "authUserID" AuthorizationHeader authorizationHeader = "authorization" B3TraceIDKey b3TraceID = "b3traceID" )
const CorrelationIDKey contextKey = "correlationID"
const ErrorMessage message = "errorMessage"
ErrorMessage is a constant used for error logging.
Variables ¶
var ( ErrorTypesStats = prometheus.NewCounterVec(prometheus.CounterOpts{ Name: "zs_server_error", Help: "Counter of HTTP Server Error", }, []string{"type", "path", "method"}) )
Functions ¶
func AllowedCORSHeader ¶
func AllowedCORSHeader() []string
AllowedCORSHeader returns the HTTP headers used for CORS configuration in web applications.
func CORS ¶
CORS an HTTP middleware that sets headers based on the provided envHeaders configuration
func ErrorResponse ¶
func ErrorResponse(w http.ResponseWriter, r *http.Request, logger logger, err errors.MultipleErrors)
ErrorResponse sends an HTTP error response, logging the error, handling various content types, and setting appropriate headers.
func ExemptPath ¶
ExemptPath checks if the path of an HTTP request matches specific patterns used for metrics, health checks, or Swagger documentation
func FetchErrResponseWithCode ¶
func FetchErrResponseWithCode(statusCode int, reason, code string) *errors.MultipleErrors
FetchErrResponseWithCode constructs an error response object. It includes a timestamp with the current time in RFC3339 format and the local time zone.
func GetDescription ¶
GetDescription maps specific error types to their corresponding descriptions and HTTP status codes.
func GetIPAddress ¶
GetIPAddress extracts and returns the client's IP address from the X-Forwarded-For header, sequence in which IPs are typically added. If the header is empty or does not contain valid IPs, it falls back to using the RemoteAddr from the request.
func LDAP ¶
LDAP middleware enables basic authentication for inter-service calls using gofr.dev LDAP
func Logging ¶
Logging is a middleware which logs response status and time in microseconds along with other data.
func NewRelic ¶
NewRelic is a middleware that registers all the endpoints and sends the data to newrelic server
func PrometheusMiddleware ¶
PrometheusMiddleware implements mux.MiddlewareFunc.
func PropagateHeaders ¶
PropagateHeaders propagates all the required headers through the context
func PushDeprecatedFeature ¶
func PushDeprecatedFeature(featureName string)
PushDeprecatedFeature increments a Prometheus metric with labels
Types ¶
type CacheEntry ¶
type CacheEntry struct {
// contains filtered or unexported fields
}
CacheEntry represents entry in LdapCache.
type LDAPOptions ¶
type LDAPOptions struct { // ex: "^/v2/promises-composite/$": MethodGroup[{Method: "POST", Group: "promises-composite-write"}] // in case same method is present in multiple elements in the array, first occurrence would be considered RegexToMethodGroup map[string][]MethodGroup // ex: ldapstage.gofr.dev:636 Addr string // TimeOut is the authentication timeout in seconds, if not set, // there is no timeout TimeOut int // CacheInvalidationFrequency sets the frequency(in seconds) with // which the in memory cache of authenticated users is reset; // if this is value not set, then there is no invalidation. // By default there is no cache invalidation CacheInvalidationFrequency int // InsecureSkipVerify controls whether a client verifies the // server's certificate chain and host name. // If InsecureSkipVerify is true, TLS accepts any certificate // presented by the server and any host name in that certificate. // In this mode, TLS is susceptible to man-in-the-middle attacks. // This should be used only for testing. InsecureSkipVerify bool }
LDAPOptions stores the configurations for LDAP middleware options
type Ldap ¶
type Ldap struct {
// contains filtered or unexported fields
}
Ldap stores configuration options and an in-memory cache for LDAP authentication.
type LdapCache ¶
type LdapCache struct {
// contains filtered or unexported fields
}
LdapCache represents the in-memory cache for LDAP authentication.
type LogDataKey ¶
type LogDataKey string
type LogLine ¶
type LogLine struct { CorrelationID string `json:"correlationId"` Type string `json:"type"` StartTimestamp time.Time `json:"startTimestamp"` Duration int64 `json:"duration"` Method string `json:"method"` IP string `json:"ip"` URI string `json:"uri"` Response int `json:"responseCode"` Headers map[string]string `json:"headers"` AppData map[string]interface{} `json:"appData"` ErrorMessage string `json:"errorMessage,omitempty"` }
LogLine represents a structured log entry, including various details like correlation ID, request method, response status, and more.
type MethodGroup ¶
MethodGroup is struct to specify HTTP methods and their associated groups.
type StatusResponseWriter ¶
type StatusResponseWriter struct { http.ResponseWriter // contains filtered or unexported fields }
StatusResponseWriter defines own Response Writer to be used for logging of status - as http.ResponseWriter does not let us read status.
func (*StatusResponseWriter) WriteHeader ¶
func (w *StatusResponseWriter) WriteHeader(status int)
WriteHeader updates the response status code and forwards the call to the underlying ResponseWriter
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package oauth provides a middleware for authenticating requests.This package provides functionality for token validation and integration with JSON Web Key (JWK) to verify JSON Web Tokens (JWT).
|
Package oauth provides a middleware for authenticating requests.This package provides functionality for token validation and integration with JSON Web Key (JWK) to verify JSON Web Tokens (JWT). |