http

package
v1.8.0 Latest Latest
Warning

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

Go to latest
Published: Jun 5, 2024 License: Apache-2.0 Imports: 33 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Accepted

func Accepted(c *fiber.Ctx, s any) error

Accepted sends an HTTP 202 Accepted response with a custom body.

func AllowFullOptionsWithCORS

func AllowFullOptionsWithCORS(app *fiber.App)

AllowFullOptionsWithCORS set r.Use(WithCORS) and allow every request to use OPTION method.

func BadRequest

func BadRequest(c *fiber.Ctx, s any) error

BadRequest sends an HTTP 400 Bad Request response with a custom body.

func Conflict

func Conflict(c *fiber.Ctx, code, message string) error

Conflict sends an HTTP 409 Conflict response with a custom code and message.

func Created

func Created(c *fiber.Ctx, s any) error

Created sends an HTTP 201 Created response with a custom body.

func DocAPI

func DocAPI(serviceName, title string, app *fiber.App)

DocAPI adds the default documentation route to the API. Ex: /{serviceName}/docs And adds the swagger route too. Ex: /{serviceName}/swagger.yaml

func File

func File(filePath string) fiber.Handler

File servers a specific file.

func Forbidden

func Forbidden(c *fiber.Ctx, message string) error

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

func GetFileFromHeader added in v1.8.0

func GetFileFromHeader(ctx *fiber.Ctx) (string, error)

GetFileFromHeader method that get file from header and give a string fom this dsl gold file

func GetPayloadFromContext

func GetPayloadFromContext(c *fiber.Ctx) any

GetPayloadFromContext retrieves the decoded request payload from the Fiber context.

func GetRemoteAddress

func GetRemoteAddress(r *http.Request) string

GetRemoteAddress returns IP address of the client making the request. It checks for X-Real-Ip or X-Forwarded-For headers which is used by Proxies.

func IPAddrFromRemoteAddr

func IPAddrFromRemoteAddr(s string) string

IPAddrFromRemoteAddr removes port information from string.

func InternalServerError

func InternalServerError(c *fiber.Ctx, message string) error

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

func JSONResponse

func JSONResponse(c *fiber.Ctx, status int, s any) error

JSONResponse sends a custom status code and body as a JSON response.

func JSONResponseError

func JSONResponseError(c *fiber.Ctx, err ResponseError) error

JSONResponseError sends a JSON formatted error response with a custom error struct.

func NoContent

func NoContent(c *fiber.Ctx) error

NoContent sends an HTTP 204 No Content response without any body.

func NotFound

func NotFound(c *fiber.Ctx, code, message string) error

NotFound sends an HTTP 404 Not Found response with a custom code and message.

func NotImplemented

func NotImplemented(c *fiber.Ctx, message string) error

NotImplemented sends an HTTP 501 Not Implemented response with a custom message.

func NotImplementedEndpoint

func NotImplementedEndpoint(c *fiber.Ctx) error

NotImplementedEndpoint returns HTTP 501 with not implemented message.

func OK

func OK(c *fiber.Ctx, s any) error

OK sends an HTTP 200 OK response with a custom body.

func PartialContent

func PartialContent(c *fiber.Ctx, s any) error

PartialContent sends an HTTP 206 Partial Content response with a custom body.

func Ping

func Ping(c *fiber.Ctx) error

Ping returns HTTP Status 200 with response "pong".

func RangeNotSatisfiable

func RangeNotSatisfiable(c *fiber.Ctx) error

RangeNotSatisfiable sends an HTTP 416 Requested Range Not Satisfiable response.

func ServeReverseProxy

func ServeReverseProxy(target string, res http.ResponseWriter, req *http.Request)

ServeReverseProxy serves a reverse proxy for a given url.

func Unauthorized

func Unauthorized(c *fiber.Ctx, code string, message string) error

Unauthorized sends an HTTP 401 Unauthorized response with a custom code and message.

func UnprocessableEntity

func UnprocessableEntity(c *fiber.Ctx, code, message string) error

UnprocessableEntity sends an HTTP 422 Unprocessable Entity response with a custom code and message.

func ValidateStruct

func ValidateStruct(s any) error

ValidateStruct validates a struct against defined validation rules, using the validator package.

func Version

func Version(version string) fiber.Handler

Version returns HTTP Status 200 with given version.

func Welcome

func Welcome(service string, description string) fiber.Handler

Welcome returns HTTP Status 200 with service info.

func WithBasicAuth

func WithBasicAuth(f BasicAuthFunc, realm string) fiber.Handler

WithBasicAuth creates a basic authentication middleware.

func WithBody

func WithBody(s any, h DecodeHandlerFunc) fiber.Handler

WithBody wraps a handler function, providing it with an instance of the specified struct.

func WithCORS

func WithCORS() fiber.Handler

WithCORS is a middleware that enables CORS. Replace it with a real CORS middleware implementation.

func WithCorrelationID

func WithCorrelationID() fiber.Handler

WithCorrelationID creates a correlation id.

func WithDecode

func WithDecode(c ConstructorFunc, h DecodeHandlerFunc) fiber.Handler

WithDecode wraps a handler function, providing it with a struct instance created using the provided constructor function.

func WithError

func WithError(c *fiber.Ctx, err error) error

WithError returns an error with the given status code and message.

func WithLog

func WithLog(opts ...LogMiddlewareOption) fiber.Handler

WithLog is a middleware to log access to http server. It logs access log according to Apache Standard Logs which uses Common Log Format (CLF) Ref: https://httpd.apache.org/docs/trunk/logs.html#common

Types

type BasicAuthFunc

type BasicAuthFunc func(username, password string) bool

BasicAuthFunc represents a func which returns if a username and password was authenticated or not. It returns true if authenticated, and false when not authenticated.

func FixedBasicAuthFunc

func FixedBasicAuthFunc(username, password string) BasicAuthFunc

FixedBasicAuthFunc is a fixed username and password to use as BasicAuthFunc.

type ConstructorFunc

type ConstructorFunc func() any

ConstructorFunc representing a constructor of any type.

type DecodeHandlerFunc

type DecodeHandlerFunc func(p any, c *fiber.Ctx) error

DecodeHandlerFunc is a handler which works with withBody decorator. It receives a struct which was decoded by withBody decorator before. Ex: json -> withBody -> DecodeHandlerFunc.

func SetBodyInContext

func SetBodyInContext(handler fiber.Handler) DecodeHandlerFunc

SetBodyInContext is a higher-order function that wraps a Fiber handler, injecting the decoded body into the request context.

type FieldValidations

type FieldValidations map[string]string

FieldValidations is a map of fields and their validation errors.

type JWKProvider

type JWKProvider struct {
	URI           string
	CacheDuration time.Duration
	// contains filtered or unexported fields
}

JWKProvider manages cryptographic public keys issued by an authorization server See https://tools.ietf.org/html/rfc7517 It's used to verify JSON Web Tokens which was signed using RS256 signing algorithm.

func (*JWKProvider) Fetch

func (p *JWKProvider) Fetch(ctx context.Context) (jwk.Set, error)

Fetch fetches (JWKS) JSON Web Key Set from authorization server and cache it

type JWTMiddleware

type JWTMiddleware struct {
	JWK *JWKProvider
}

JWTMiddleware represents a middleware which protects endpoint using JWT tokens.

func NewJWTMiddleware

func NewJWTMiddleware(jwkURI string) *JWTMiddleware

NewJWTMiddleware create an instance of JWTMiddleware It uses JWK cache duration of 1 hour.

func (*JWTMiddleware) Protect

func (m *JWTMiddleware) Protect() fiber.Handler

Protect protects any endpoint using JWT tokens.

func (*JWTMiddleware) WithScope

func (m *JWTMiddleware) WithScope(scopes []string) fiber.Handler

WithScope verify if a requester has the required scope to access an endpoint.

type LogMiddlewareOption

type LogMiddlewareOption func(l *logMiddleware)

LogMiddlewareOption represents the log middleware function as an implementation.

func WithLogger

func WithLogger(logger mlog.Logger) LogMiddlewareOption

WithLogger is a functional option for logMiddleware.

type OAuth2JWTToken

type OAuth2JWTToken struct {
	Token    *jwt.Token
	Claims   jwt.MapClaims
	Groups   []string
	Sub      string
	Username *string
	Scope    string
	ScopeSet map[string]bool
}

OAuth2JWTToken represents a self-contained way for securely transmitting information between parties as a JSON object https://tools.ietf.org/html/rfc7519

func TokenFromContext

func TokenFromContext(c *fiber.Ctx) (*OAuth2JWTToken, error)

TokenFromContext extracts a JWT token from context.

type PayloadContextValue

type PayloadContextValue string

PayloadContextValue is a wrapper type used to keep Context.Locals safe.

type ProfileID

type ProfileID string

ProfileID is the profileID type of a member.

type QueryHeader added in v1.8.0

type QueryHeader struct {
	Metadata    *bson.M
	Limit       int
	Page        int
	UseMetadata bool
}

QueryHeader entity from query parameter from get apis

func ValidateParameters added in v1.8.0

func ValidateParameters(params map[string]string) *QueryHeader

ValidateParameters validate and return struct of default parameters

type RequestInfo

type RequestInfo struct {
	Method        string
	Username      string
	URI           string
	Referer       string
	RemoteAddress string
	Status        int
	Date          time.Time
	Duration      time.Duration
	UserAgent     string
	CorrelationID string
	Protocol      string
	Size          int
	Body          string
}

RequestInfo is a struct design to store http access log data.

func NewRequestInfo

func NewRequestInfo(c *fiber.Ctx) *RequestInfo

NewRequestInfo creates an instance of RequestInfo.

func (*RequestInfo) CLFString

func (r *RequestInfo) CLFString() string

CLFString produces a log entry format similar to Common Log Format (CLF) Ref: https://httpd.apache.org/docs/trunk/logs.html#common

func (*RequestInfo) FinishRequestInfo

func (r *RequestInfo) FinishRequestInfo(rw *ResponseMetricsWrapper)

FinishRequestInfo calculates the duration of RequestInfo automatically using time.Now() It also set StatusCode and Size of RequestInfo passed by ResponseMetricsWrapper.

func (*RequestInfo) String

func (r *RequestInfo) String() string

String implements fmt.Stringer interface and produces a log entry using RequestInfo.CLFExtendedString.

type ResponseError

type ResponseError struct {
	Code    int     `json:"code,omitempty"`
	Message string  `json:"message,omitempty"`
	Origin  *string `json:"origin,omitempty"`
}

ResponseError is a struct used to return errors to the client.

func (ResponseError) Error

func (r ResponseError) Error() string

Error returns the message of the ResponseError.

No parameters. Returns a string.

type ResponseMetricsWrapper

type ResponseMetricsWrapper struct {
	Context    *fiber.Ctx
	StatusCode int
	Size       int
	Body       string
}

ResponseMetricsWrapper is a Wrapper responsible for collect the response data such as status code and size It implements built-in ResponseWriter interface.

type TokenContextValue

type TokenContextValue string

TokenContextValue is a wrapper type used to keep Context.Locals safe.

type ValidationError

type ValidationError struct {
	EntityType string           `json:"entityType,omitempty"`
	Title      string           `json:"title,omitempty"`
	Code       string           `json:"code,omitempty"`
	Message    string           `json:"message,omitempty"`
	Fields     FieldValidations `json:"fields,omitempty"`
}

ValidationError records an error indicating an entity was not found in any case that caused it.

func (ValidationError) Error

func (r ValidationError) Error() string

Error returns the error message for a ValidationError.

No parameters. Returns a string.

Jump to

Keyboard shortcuts

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