prefix
stringlengths
512
512
suffix
stringlengths
256
256
middle
stringlengths
14
229
meta
dict
redactedValue = "[redacted]" // isOriginSerializedOrNull checks if the origin is a serialized origin or the literal "null". // It returns two booleans: (isSerialized, isNull). func isOriginSerializedOrNull(originHeaderRaw string) (isSerialized, isNull bool) { //nolint:nonamedreturns // gocritic unnamedResult prefers n...
s if len(cfg.AllowMethods) == 0 { cfg.AllowMethods = ConfigDefault.AllowMethods } } redactValues := !cfg.DisableValueRedaction maskValue := func(value string) string { if redactValues { return redactedValue } return value } // Warni
e } // New creates a new middleware handler func New(config ...Config) fiber.Handler { // Set default config cfg := ConfigDefault // Override config if provided if len(config) > 0 { cfg = config[0] // Set default value
{ "filepath": "middleware/cors/cors.go", "language": "go", "file_size": 8222, "cut_index": 716, "middle_length": 229 }
. type Config struct { // Next defines a function to skip middleware. // Optional. Default: nil Next func(fiber.Ctx) bool // XSSProtection // Optional. Default value "0". XSSProtection string // ContentTypeNosniff // Optional. Default value "nosniff". ContentTypeNosniff string // XFrameOptions // Optional...
lt value "require-corp". CrossOriginEmbedderPolicy string // Cross-Origin-Opener-Policy // Optional. Default value "same-origin". CrossOriginOpenerPolicy string // Cross-Origin-Resource-Policy // Optional. Default value "same-origin". CrossOriginR
y string // ReferrerPolicy // Optional. Default value "no-referrer". ReferrerPolicy string // Permissions-Policy // Optional. Default value "". PermissionPolicy string // Cross-Origin-Embedder-Policy // Optional. Defau
{ "filepath": "middleware/helmet/config.go", "language": "go", "file_size": 3680, "cut_index": 614, "middle_length": 229 }
.com/gofiber/fiber/v3/extractors" "github.com/gofiber/fiber/v3/internal/redact" "github.com/gofiber/fiber/v3/middleware/logger" "github.com/gofiber/utils/v2" ) // The contextKey type is unexported to prevent collisions with context keys defined in // other packages. type contextKey int // The keys for the values i...
fault(config...) // Determine the auth schemes from the extractor chain. authSchemes := getAuthSchemes(cfg.Extractor) // Return middleware handler return func(c fiber.Ctx) error { // Filter request to skip middleware if cfg.Next != nil && cfg.Nex
alid API Key") var registerLogContextTagsOnce sync.Once // New creates a new middleware handler func New(config ...Config) fiber.Handler { registerLogContextTagsOnce.Do(registerLogContextTags) // Init config cfg := configDe
{ "filepath": "middleware/keyauth/keyauth.go", "language": "go", "file_size": 3790, "cut_index": 614, "middle_length": 229 }
om/gofiber/fiber/v3" "github.com/stretchr/testify/require" ) var testConfig = fiber.TestConfig{ Timeout: 5 * time.Second, FailOnTimeout: true, } func Test_Non_Pprof_Path(t *testing.T) { app := fiber.New() app.Use(New()) app.Get("/", func(c fiber.Ctx) error { return c.SendString("escaped") }) resp, ...
ing("escaped") }) resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, "escaped", stri
rr) require.Equal(t, "escaped", string(b)) } func Test_Non_Pprof_Path_WithPrefix(t *testing.T) { app := fiber.New() app.Use(New(Config{Prefix: "/federated-fiber"})) app.Get("/", func(c fiber.Ctx) error { return c.SendStr
{ "filepath": "middleware/pprof/pprof_test.go", "language": "go", "file_size": 4981, "cut_index": 614, "middle_length": 229 }
t(fiber.MethodGet, "/", http.NoBody) req.Header.Set("Accept-Encoding", "gzip") resp, err := app.Test(req, testConfig) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") require.Equal(t, "gzip", resp.Header.Get(fiber.HeaderContentEncoding)) // Validate that the file si...
evels { t.Run(fmt.Sprintf("%s_level %d", algo, level), func(t *testing.T) { t.Parallel() app := fiber.New() app.Use(New(Config{Level: level})) app.Get("/", func(c fiber.Ctx) error { c.Set(fiber.HeaderContentType, fiber.MIMETextPla
ent_Level(t *testing.T) { t.Parallel() levels := []Level{LevelDefault, LevelBestSpeed, LevelBestCompression} algorithms := []string{"gzip", "deflate", "br", "zstd"} for _, algo := range algorithms { for _, level := range l
{ "filepath": "middleware/compress/compress_test.go", "language": "go", "file_size": 25309, "cut_index": 1331, "middle_length": 229 }
port ( "github.com/gofiber/fiber/v3" ) // Config defines the config for middleware. type Config struct { // Next defines a function to skip this middleware when returned true. // // Optional. Default: nil Next func(c fiber.Ctx) bool // Custom function to encrypt cookies. // // Optional. Default: EncryptCookie...
d DecryptCookie functions. // You may use `encryptcookie.GenerateKey(length)` to generate a new key. Key string // Array of cookie keys that should not be encrypted. // // Optional. Default: [] Except []string } // ConfigDefault is the default conf
func(name, encryptedString, key string) (string, error) // Base64 encoded unique key to encode & decode cookies. // // Required. Key length should be 16, 24, or 32 bytes when decoded // if using the default EncryptCookie an
{ "filepath": "middleware/encryptcookie/config.go", "language": "go", "file_size": 1838, "cut_index": 537, "middle_length": 229 }
port ( "errors" "github.com/valyala/fasthttp" "github.com/gofiber/fiber/v3" ) // New creates a new middleware handler func New(config ...Config) fiber.Handler { // Set default config cfg := configDefault(config...) // Return new handler return func(c fiber.Ctx) error { // Don't execute middleware if Next r...
} else { c.Request().Header.SetCookie(keyString, decryptedValue) } } } // Delete cookies that failed to decrypt - outside the loop to avoid mutation during iteration for _, key := range cookiesToDelete { c.Request().Header.DelCoo
ookies() { keyString := string(key) if !isDisabled(keyString, cfg.Except) { decryptedValue, err := cfg.Decryptor(keyString, string(value), cfg.Key) if err != nil { cookiesToDelete = append(cookiesToDelete, key)
{ "filepath": "middleware/encryptcookie/encryptcookie.go", "language": "go", "file_size": 1966, "cut_index": 537, "middle_length": 229 }
/ matchScheme compares the scheme of the domain and pattern func matchScheme(domain, pattern string) bool { dScheme, _, dFound := strings.Cut(domain, ":") pScheme, _, pFound := strings.Cut(pattern, ":") return dFound && pFound && dScheme == pScheme } // normalizeDomain removes the scheme and port from the input dom...
malizeOrigin checks if the provided origin is in a correct format // and normalizes it by removing any path or trailing slash. // It returns a boolean indicating whether the origin is valid // and the normalized origin. func normalizeOrigin(origin string)
(input, "http://"); found { input = after } // Find and remove port, if present if input != "" && input[0] != '[' { if before, _, found := strings.Cut(input, ":"); found { input = before } } return input } // nor
{ "filepath": "middleware/cors/utils.go", "language": "go", "file_size": 3208, "cut_index": 614, "middle_length": 229 }
fiber/fiber/v3/extractors" ) const ( ErrorInvalidRequest = "invalid_request" ErrorInvalidToken = "invalid_token" ErrorInsufficientScope = "insufficient_scope" ) // Config defines the config for middleware. type Config struct { // Next defines a function to skip this middleware when returned true. // // ...
a function to validate the key. // // Required. Validator func(c fiber.Ctx, key string) (bool, error) // Realm defines the protected area for WWW-Authenticate responses. // This is used to set the `WWW-Authenticate` header when authentication fails.
// ErrorHandler defines a function which is executed for an invalid key. // It may be used to define a custom error. // // Optional. Default: 401 Missing or invalid API Key ErrorHandler fiber.ErrorHandler // Validator is
{ "filepath": "middleware/keyauth/config.go", "language": "go", "file_size": 4882, "cut_index": 614, "middle_length": 229 }
ddleware/etag" "github.com/gofiber/utils/v2" "github.com/valyala/fasthttp" ) func hasToken(header, token string) bool { for part := range strings.SplitSeq(header, ",") { if utils.EqualFold(utils.TrimSpace(part), token) { return true } } return false } func shouldSkip(c fiber.Ctx) bool { if c.Method() == ...
{ return true } // Skip body length check for streaming responses to avoid materializing the stream if !c.Response().IsBodyStream() && len(c.Response().Body()) == 0 { return true } return false } func appendVaryAcceptEncoding(c fiber.Ctx) { va
tusNotModified || status == fiber.StatusPartialContent || c.Get(fiber.HeaderRange) != "" || hasToken(c.Get(fiber.HeaderCacheControl), "no-transform") || hasToken(c.GetRespHeader(fiber.HeaderCacheControl), "no-transform")
{ "filepath": "middleware/compress/compress.go", "language": "go", "file_size": 3075, "cut_index": 614, "middle_length": 229 }
e compress import ( "github.com/gofiber/fiber/v3" ) // Config defines the config for middleware. type Config struct { // Next defines a function to skip this middleware when returned true. // // Optional. Default: nil Next func(c fiber.Ctx) bool // Level sets the compression level used for the response // //...
Compression Level = 2 ) // ConfigDefault is the default config var ConfigDefault = Config{ Next: nil, Level: LevelDefault, } // Helper function to set default values func configDefault(config ...Config) Config { // Return default config if nothing pr
entation of compression level type Level int // Represents compression level that will be used in the middleware const ( LevelDisabled Level = -1 LevelDefault Level = 0 LevelBestSpeed Level = 1 LevelBest
{ "filepath": "middleware/compress/config.go", "language": "go", "file_size": 1248, "cut_index": 518, "middle_length": 229 }
ge encryptcookie import ( "crypto/rand" "encoding/base64" "fmt" "testing" "github.com/stretchr/testify/require" ) func Test_configDefault_KeyValidation(t *testing.T) { t.Parallel() t.Run("invalid base64", func(t *testing.T) { t.Parallel() _, decErr := base64.StdEncoding.DecodeString("invalid") expected...
sting.T) { t.Parallel() key := make([]byte, 20) _, err := rand.Read(key) require.NoError(t, err) invalidKey := base64.StdEncoding.EncodeToString(key) require.PanicsWithValue(t, ErrInvalidKeyLength, func() { configDefault(Config{Key: invalidK
h", func(t *te
{ "filepath": "middleware/encryptcookie/config_test.go", "language": "go", "file_size": 803, "cut_index": 517, "middle_length": 14 }
g.T) { t.Parallel() key := make([]byte, tt.length) _, err := rand.Read(key) require.NoError(t, err) keyString := base64.StdEncoding.EncodeToString(key) _, err = EncryptCookie("test", "SomeThing", keyString) require.Error(t, err) }) t.Run(strconv.Itoa(tt.length)+"_length_decrypt", func(t *test...
Parallel() _, err := EncryptCookie("test", "SomeText", invalidBase64) require.Error(t, err) require.ErrorContains(t, err, "failed to base64-decode key") }) t.Run("decryptor_key", func(t *testing.T) { t.Parallel() _, err := DecryptCookie("test"
kie("test", "SomeThing", keyString) require.Error(t, err) }) } } func Test_Middleware_InvalidBase64(t *testing.T) { t.Parallel() invalidBase64 := "invalid-base64-string-!@#" t.Run("encryptor", func(t *testing.T) { t.
{ "filepath": "middleware/encryptcookie/encryptcookie_test.go", "language": "go", "file_size": 19879, "cut_index": 1331, "middle_length": 229 }
/v3" fiberlog "github.com/gofiber/fiber/v3/log" ) // fiberMiddlewareTags lists the context tag names that Fiber's built-in // middlewares register through RegisterContextTag. They are pre-registered // here as no-op stubs so a logger format that references e.g. ${api-key} // compiles even when the corresponding middl...
/ renames in one place cascade automatically. var fiberMiddlewareTags = []string{ fiberlog.TagAPIKey, fiberlog.TagCSRFToken, fiberlog.TagRequestIDDashed, fiberlog.TagRequestID, fiberlog.TagSessionID, fiberlog.TagUsername, } func init() { for _, nam
er instance if the tag should render non-empty values. Existing logger // middleware instances keep the function chain they compiled at construction. // // The names are sourced from the canonical fiberlog tag constants so that /
{ "filepath": "middleware/logger/context_tag.go", "language": "go", "file_size": 2363, "cut_index": 563, "middle_length": 229 }
"github.com/gofiber/fiber/v3/internal/logtemplate" "github.com/stretchr/testify/require" ) func Test_UnknownTagErrorIsAndAs(t *testing.T) { t.Parallel() err := &UnknownTagError{Tag: "method"} require.ErrorIs(t, err, ErrUnknownTag) var typed *UnknownTagError require.ErrorAs(t, err, &typed) require.Equal(t, "m...
e"}) var typed *UnknownTagError require.ErrorAs(t, got, &typed) require.Equal(t, "missing:value", typed.Tag) require.Equal(t, "value", typed.Param) require.ErrorIs(t, got, ErrUnknownTag) require.NoError(t, translateBuildError(errors.New("unrelated")
e.UnknownTagError{Tag: "missing:value", Param: "valu
{ "filepath": "middleware/logger/errors_test.go", "language": "go", "file_size": 872, "cut_index": 559, "middle_length": 52 }
er import ( "errors" "strconv" "github.com/gofiber/fiber/v3/internal/logtemplate" ) // ErrUnknownTag indicates that the logger middleware was configured with a // format that references a tag with no registered renderer. var ErrUnknownTag = errors.New("logger: unknown template tag") // UnknownTagError is the typ...
nownTagError) Error() string { msg := ErrUnknownTag.Error() + ": " + strconv.Quote(e.Tag) if e.Hint != "" { msg += " (" + e.Hint + ")" } return msg } func (*UnknownTagError) Unwrap() error { return ErrUnknownTag } // translateBuildError converts a
metric (empty for bare tags); Hint, when non-empty, is a human- // readable suggestion (e.g. parametric form for a likely-mistyped bare tag). type UnknownTagError struct { Tag string Param string Hint string } func (e *Unk
{ "filepath": "middleware/logger/errors.go", "language": "go", "file_size": 1348, "cut_index": 524, "middle_length": 229 }
ber/fiber/v3" "github.com/gofiber/fiber/v3/internal/logtemplate" ) // defaultErrPadding is the initial column width used by the default access-log // formatter to align the request path against the optional error suffix. The // width grows on first request to fit the longest registered route, but a // non-zero defaul...
mat contains latency cfg.isLatencyEnabled = strings.Contains(cfg.Format, "${"+TagLatency+"}") var timestamp atomic.Value // Create correct timeformat timestamp.Store(time.Now().In(cfg.timeZoneLocation).Format(cfg.TimeFormat)) // Update date/time eve
cfg := configDefault(config...) // Get timezone location tz, err := time.LoadLocation(cfg.TimeZone) if err != nil || tz == nil { cfg.timeZoneLocation = time.Local } else { cfg.timeZoneLocation = tz } // Check if for
{ "filepath": "middleware/logger/logger.go", "language": "go", "file_size": 4017, "cut_index": 614, "middle_length": 229 }
"host" TagMethod = "method" TagPath = "path" TagURL = "url" TagUA = "ua" TagLatency = "latency" TagStatus = "status" TagResBody = "resBody" TagReqHeaders = "reqHeaders" TagQueryStringParams = "queryParams" TagBody ...
"red" TagGreen = "green" TagYellow = "yellow" TagBlue = "blue" TagMagenta = "magenta" TagCyan = "cyan" TagWhite = "white" TagReset = "reset" ) // ErrTagInvalid is re
" TagRespHeader = "respHeader:" TagLocals = "locals:" TagQuery = "query:" TagForm = "form:" TagCookie = "cookie:" TagBlack = "black" TagRed =
{ "filepath": "middleware/logger/tags.go", "language": "go", "file_size": 9243, "cut_index": 921, "middle_length": 229 }
e timeout import ( "time" "github.com/gofiber/fiber/v3" ) // Config holds the configuration for the timeout middleware. type Config struct { // Next defines a function to skip this middleware. // Optional. Default: nil Next func(c fiber.Ctx) bool // OnTimeout is executed when a timeout occurs. // Optional. D...
, Errors: nil, } // configDefault returns the first Config value or ConfigDefault. func configDefault(config ...Config) Config { if len(config) < 1 { return ConfigDefault } cfg := config[0] if cfg.Timeout < 0 { cfg.Timeout = ConfigDefault.Ti
fines the timeout duration for all routes. // Optional. Default: 0 (no timeout) Timeout time.Duration } // ConfigDefault is the default configuration. var ConfigDefault = Config{ Next: nil, Timeout: 0, OnTimeout: nil
{ "filepath": "middleware/timeout/config.go", "language": "go", "file_size": 1218, "cut_index": 518, "middle_length": 229 }
ream is a writer where logs are written // // Default: os.Stdout Stream io.Writer // Next defines a function to skip this middleware when returned true. // // Optional. Default: nil Next func(c fiber.Ctx) bool // Skip is a function to determine if logging is skipped or written to Stream. // // Optional. Def...
tomTags map[string]LogFunc // You can define specific things before returning the handler: colors, template, etc. // // Optional. Default: beforeHandlerFunc BeforeHandlerFunc func(*Config) // You can use custom loggers with Fiber by using this field
l. Default: nil Done func(c fiber.Ctx, logString []byte) // CustomTags defines per-middleware tag functions. // CustomTags override built-in and globally registered tags with the same name. // // Optional. Default: nil Cus
{ "filepath": "middleware/logger/config.go", "language": "go", "file_size": 5710, "cut_index": 716, "middle_length": 229 }
fiber/fiber/v3/internal/logtemplate" "github.com/mattn/go-colorable" "github.com/mattn/go-isatty" "github.com/valyala/bytebufferpool" ) // default logger for fiber func defaultLoggerInstance(c fiber.Ctx, data *Data, cfg *Config) error { if cfg == nil { cfg = &Config{ Stream: os.Stdout, Format: ...
== DefaultFormat { // Format error if exist formatErr := "" if cfg.areColorsEnabled { if data.ChainErr != nil { formatErr = colors.Red + " | " + data.ChainErr.Error() + colors.Reset } fmt.Fprintf( buf, "%s |%s %3d %s| %13v | %15s
il // Skip logging if Skip returns true } // Alias colors colors := c.App().Config().ColorScheme // Get new buffer buf := bytebufferpool.Get() // Default output when no custom Format or io.Writer is given if cfg.Format
{ "filepath": "middleware/logger/default_logger.go", "language": "go", "file_size": 4773, "cut_index": 614, "middle_length": 229 }
gger_locals func Test_Logger_locals(t *testing.T) { t.Parallel() app := fiber.New() buf := bytebufferpool.Get() defer bytebufferpool.Put(buf) app.Use(New(Config{ Format: "${locals:demo}", Stream: buf, })) app.Get("/", func(c fiber.Ctx) error { c.Locals("demo", "johndoe") return c.SendStatus(fiber.Stat...
resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/int", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) require.Equal(t, "55", buf.String()) buf.Reset() resp, err = app.Test(httptest.NewRequest(fibe
.StatusOK) }) resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) require.Equal(t, "johndoe", buf.String()) buf.Reset()
{ "filepath": "middleware/logger/logger_test.go", "language": "go", "file_size": 41252, "cut_index": 2151, "middle_length": 229 }
equest's // context with one that has the configured deadline, which is exposed through // c.Context(). Handlers can detect the timeout by listening on c.Context().Done() // and return early. // // When a timeout occurs, the middleware returns immediately with fiber.ErrRequestTimeout // (or the result of OnTimeout if c...
ut context - handler can check c.Context().Done() parent := ctx.Context() tCtx, cancel := context.WithTimeout(parent, timeout) ctx.SetContext(tCtx) // Channels for handler result and panics done := make(chan error, 1) panicChan := make(chan an
er.Handler { cfg := configDefault(config...) return func(ctx fiber.Ctx) error { if cfg.Next != nil && cfg.Next(ctx) { return h(ctx) } timeout := cfg.Timeout if timeout <= 0 { return h(ctx) } // Create timeo
{ "filepath": "middleware/timeout/timeout.go", "language": "go", "file_size": 5910, "cut_index": 716, "middle_length": 229 }
ackage logger const ( // Fiber's default logger DefaultFormat = "[${time}] ${ip} ${status} - ${latency} ${method} ${path} ${error}\n" // Apache Common Log Format (CLF) CommonFormat = "${ip} - - [${time}] \"${method} ${url} ${protocol}\" ${status} ${bytesSent}\n" // Apache Combined Log Format CombinedFormat = "${...
"http\":{\"request\":{\"method\":\"${method}\",\"url\":\"${url}\",\"protocol\":\"${protocol}\"},\"response\":{\"status_code\":${status},\"body\":{\"bytes\":${bytesSent}}}},\"log\":{\"level\":\"INFO\",\"logger\":\"fiber\"},\"message\":\"${method} ${url} res
method}\",\"url\":\"${url}\",\"status\":${status},\"bytesSent\":${bytesSent}}\n" // Elastic Common Schema (ECS) Log Format ECSFormat = "{\"@timestamp\":\"${time}\",\"ecs\":{\"version\":\"1.6.0\"},\"client\":{\"ip\":\"${ip}\"},\
{ "filepath": "middleware/logger/format.go", "language": "go", "file_size": 1028, "cut_index": 513, "middle_length": 229 }
r/fiber/v3" fiberlog "github.com/gofiber/fiber/v3/log" "github.com/gofiber/utils/v2" ) func methodColor(method string, colors *fiber.Colors) string { if colors == nil { return "" } switch method { case fiber.MethodGet: return colors.Cyan case fiber.MethodPost: return colors.Green case fiber.MethodPut: ...
return colors.Green case code >= fiber.StatusMultipleChoices && code < fiber.StatusBadRequest: return colors.Blue case code >= fiber.StatusBadRequest && code < fiber.StatusInternalServerError: return colors.Yellow default: return colors.Red } }
eturn colors.Blue default: return colors.Reset } } func statusColor(code int, colors *fiber.Colors) string { if colors == nil { return "" } switch { case code >= fiber.StatusOK && code < fiber.StatusMultipleChoices:
{ "filepath": "middleware/logger/utils.go", "language": "go", "file_size": 2533, "cut_index": 563, "middle_length": 229 }
"github.com/gofiber/fiber/v3" "github.com/gofiber/fiber/v3/middleware/logger" "github.com/gofiber/utils/v2" "golang.org/x/text/unicode/norm" ) // The contextKey type is unexported to prevent collisions with context keys defined in // other packages. type contextKey int // The key for the username value stored i...
Don't execute middleware if Next returns true if cfg.Next != nil && cfg.Next(c) { return c.Next() } // Get authorization header and ensure it matches the Basic scheme rawAuth := c.Get(fiber.HeaderAuthorization) if rawAuth == "" { return cf
) fiber.Handler { registerLogContextTagsOnce.Do(registerLogContextTags) // Set default config cfg := configDefault(config...) var cerr base64.CorruptInputError // Return new handler return func(c fiber.Ctx) error { //
{ "filepath": "middleware/basicauth/basicauth.go", "language": "go", "file_size": 4159, "cut_index": 614, "middle_length": 229 }
ection via flush errors. // Application-specific concerns such as topics, replay storage, authentication, // and pub/sub fan-out intentionally stay outside the core middleware. package sse import ( "bufio" "context" "errors" "fmt" "sync" "time" "github.com/gofiber/fiber/v3" "github.com/gofiber/utils/v2" ) va...
"X-Accel-Buffering", "no") streamContext := c.Context() lastEventID := c.Get(fiber.HeaderLastEventID) c.Abandon() return c.SendStreamWriter(func(w *bufio.Writer) { stream := newStream(streamContext, w, lastEventID, c.App().Config().JSONEncode
anic("sse: Handler must not be nil") } return func(c fiber.Ctx) error { c.Set(fiber.HeaderContentType, mimeTextEventStream) c.Set(fiber.HeaderCacheControl, "no-cache") c.Set(fiber.HeaderConnection, "keep-alive") c.Set(
{ "filepath": "middleware/sse/sse.go", "language": "go", "file_size": 5338, "cut_index": 716, "middle_length": 229 }
tify/require" "github.com/valyala/fasthttp" ) func Test_GetAndPutToThePool(t *testing.T) { t.Parallel() // Panics in case we get from another pool require.Panics(t, func() { _ = GetFromThePool[*HeaderBinding](&CookieBinderPool) }) // We get from the pool binder := GetFromThePool[*HeaderBinding](&HeaderBinde...
GetFromThePool[*MsgPackBinding](&MsgPackBinderPool) } func Test_Binders_ErrorPaths(t *testing.T) { t.Run("query binder invalid key", func(t *testing.T) { b := &QueryBinding{} req := fasthttp.AcquireRequest() req.URI().SetQueryString("invalid[%3Dval
nding](&FormBinderPool) _ = GetFromThePool[*URIBinding](&URIBinderPool) _ = GetFromThePool[*XMLBinding](&XMLBinderPool) _ = GetFromThePool[*JSONBinding](&JSONBinderPool) _ = GetFromThePool[*CBORBinding](&CBORBinderPool) _ =
{ "filepath": "binder/binder_test.go", "language": "go", "file_size": 4687, "cut_index": 614, "middle_length": 229 }
ErrTokenInvalid = errors.New("csrf: token invalid") ErrFetchSiteInvalid = errors.New("csrf: sec-fetch-site header invalid") ErrRefererNotFound = errors.New("csrf: referer header missing") ErrRefererInvalid = errors.New("csrf: referer header invalid") ErrRefererNoMatch = errors.New("csrf: referer does not...
token storage. The actual token validation relies on the key, not this value. ) var registerLogContextTagsOnce sync.Once // Handler for CSRF middleware type Handler struct { sessionManager *sessionManager storageManager *storageManager config
riginNotFound = errors.New("origin not supplied or is null") // internal error, will not be returned to the user dummyValue = []byte{'+'} // dummyValue is a placeholder value stored in
{ "filepath": "middleware/csrf/csrf.go", "language": "go", "file_size": 13169, "cut_index": 921, "middle_length": 229 }
ntains(t, captured, "csrf: failed to fetch token from storage") } func TestCSRFStorageSetError(t *testing.T) { t.Parallel() storage := newFailingCSRFStorage() storage.errs["set|token"] = errors.New("boom") var captured error app := fiber.New() app.Use(New(Config{ Storage: storage, KeyGenerator: func() str...
Contains(t, captured, "csrf: failed to store token in storage") } func TestCSRFStorageDeleteError(t *testing.T) { t.Parallel() storage := newFailingCSRFStorage() storage.data["token"] = []byte("value") storage.errs["del|token"] = errors.New("boom")
Status(fiber.StatusOK) }) resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusTeapot, resp.StatusCode) require.Error(t, captured) require.Error
{ "filepath": "middleware/csrf/csrf_test.go", "language": "go", "file_size": 77307, "cut_index": 3790, "middle_length": 229 }
Static_Direct(t *testing.T) { t.Parallel() app := fiber.New() app.Get("/*", New("../../.github")) resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/index.html", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") require.NotEmpty(t, resp.Heade...
de") require.NotEmpty(t, resp.Header.Get(fiber.HeaderContentLength)) require.Equal(t, fiber.MIMETextPlainCharsetUTF8, resp.Header.Get(fiber.HeaderContentType)) resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/testdata/testRoutes.json", http.
ire.Contains(t, string(body), "Hello, World!") resp, err = app.Test(httptest.NewRequest(fiber.MethodPost, "/index.html", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 405, resp.StatusCode, "Status co
{ "filepath": "middleware/static/static_test.go", "language": "go", "file_size": 48161, "cut_index": 2151, "middle_length": 229 }
b.com/gofiber/utils/v2" ) // Config defines the config for CSRF middleware. type Config struct { // Storage is used to store the state of the middleware. // // Optional. Default: memory.New() // Ignored if Session is set. Storage fiber.Storage // Next defines a function to skip this middleware when returned tru...
turned from fiber.Handler. // // Optional. Default: defaultErrorHandler ErrorHandler fiber.ErrorHandler // CookieName is the name of the CSRF cookie. // // Optional. Default: "csrf_" CookieName string // CookieDomain is the domain of the CSRF coo
session store instead of the storage. Session *session.Store // KeyGenerator creates a new CSRF token. // // Optional. Default: utils.SecureToken KeyGenerator func() string // ErrorHandler is executed when an error is re
{ "filepath": "middleware/csrf/config.go", "language": "go", "file_size": 6990, "cut_index": 716, "middle_length": 229 }
T) { t.Parallel() secureConfigs := []Config{ {Extractor: extractors.FromHeader("X-Csrf-Token")}, {Extractor: extractors.FromForm("_csrf")}, {Extractor: extractors.FromQuery("csrf_token")}, {Extractor: extractors.FromParam("csrf")}, {Extractor: extractors.Chain(extractors.FromHeader("X-Csrf-Token"), e...
ecureCookieExtractor := extractors.Extractor{ Extract: func(c fiber.Ctx) (string, error) { return c.Cookies("csrf_"), nil }, Source: extractors.SourceCookie, Key: "csrf_", } cfg := Config{ CookieName: "csrf_", Extractor: inse
}) }) } }) // Test insecure configurations - should panic t.Run("InsecureCookieExtractor", func(t *testing.T) { t.Parallel() // Create a custom extractor that reads from cookie (simulating dangerous behavior) ins
{ "filepath": "middleware/csrf/config_test.go", "language": "go", "file_size": 10555, "cut_index": 921, "middle_length": 229 }
asthttp" "github.com/gofiber/fiber/v3" ) var ErrInvalidPath = errors.New("invalid path") const invalidPathSentinel = "/__fiber_invalid__" func bytesToPathString(p []byte) string { if bytes.IndexByte(p, '\\') >= 0 { b := make([]byte, len(p)) copy(b, p) for i := range b { if b[i] == '\\' { b[i] = '/' ...
= nil { return false, err } trimmed := utils.TrimLeft(filepath.ToSlash(s), '/') for trimmed != "" { segment, rest, found := strings.Cut(trimmed, "/") if segment == ".." { return true, nil } if !found { return false, nil } trimmed =
ape(s) if err != nil { return "", ErrInvalidPath } if us == s { break } s = us } return s, nil } func hasParentDirSegment(p []byte) (bool, error) { s, err := unescapePathString(bytesToPathString(p)) if err !
{ "filepath": "middleware/static/static.go", "language": "go", "file_size": 8787, "cut_index": 716, "middle_length": 229 }
in string expectedOrigin string expectedValid bool }{ {origin: "http://example.com", expectedValid: true, expectedOrigin: "http://example.com"}, // Simple case should work. {origin: "HTTP://EXAMPLE.COM", expectedValid: true, expectedOrigin: "http://example.com"}, ...
le.com:3000"}, // Trailing slash should be removed. {origin: "http://", expectedValid: false, expectedOrigin: ""}, // Invalid origin should not be accepted. {origin: "file:///etc/passwd", exp
rigin: "http://example.com:3000", expectedValid: true, expectedOrigin: "http://example.com:3000"}, // Port should be preserved. {origin: "http://example.com:3000/", expectedValid: true, expectedOrigin: "http://examp
{ "filepath": "middleware/csrf/helpers_test.go", "language": "go", "file_size": 8861, "cut_index": 716, "middle_length": 229 }
r/fiber/v3" "github.com/gofiber/fiber/v3/log" "github.com/gofiber/fiber/v3/middleware/session" ) type sessionManager struct { session *session.Store } type sessionKeyType int const ( sessionKey sessionKeyType = 0 ) func newSessionManager(s *session.Store) *sessionManager { // Create new storage handler sessio...
if sess != nil { token, ok = sess.Get(sessionKey).(Token) } else { // Try to get the session from the store storeSess, err := m.session.Get(c) if err != nil { // Handle error return nil } token, ok = storeSess.Get(sessionKey).(Token) }
pe(0)) s.RegisterType(Token{}) } return sessionManager } // get token from session func (m *sessionManager) getRaw(c fiber.Ctx, key string, raw []byte) []byte { sess := session.FromContext(c) var token Token var ok bool
{ "filepath": "middleware/csrf/session_manager.go", "language": "go", "file_size": 2372, "cut_index": 563, "middle_length": 229 }
EDIT. package csrf import ( "bytes" "testing" "github.com/tinylib/msgp/msgp" ) func TestMarshalUnmarshalitem(t *testing.T) { v := item{} bts, err := v.MarshalMsg(nil) if err != nil { t.Fatal(err) } left, err := v.UnmarshalMsg(bts) if err != nil { t.Fatal(err) } if len(left) > 0 { t.Errorf("%d byte...
ts := make([]byte, 0, v.Msgsize()) bts, _ = v.MarshalMsg(bts[0:0]) b.SetBytes(int64(len(bts))) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { bts, _ = v.MarshalMsg(bts[0:0]) } } func BenchmarkUnmarshalitem(b *testing.B) { v := item{}
len(left), left) } } func BenchmarkMarshalMsgitem(b *testing.B) { v := item{} b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { v.MarshalMsg(nil) } } func BenchmarkAppendMsgitem(b *testing.B) { v := item{} b
{ "filepath": "middleware/csrf/storage_manager_msgp_test.go", "language": "go", "file_size": 2235, "cut_index": 563, "middle_length": 229 }
/utils/v2/strings" "github.com/gofiber/fiber/v3" "github.com/gofiber/fiber/v3/log" ) // Inspired by https://datatracker.ietf.org/doc/html/draft-ietf-httpapi-idempotency-key-header-02 // and https://github.com/penguin-statistics/backend-next/blob/f2f7d5ba54fc8a58f168d153baa17b2ad4a14e45/internal/pkg/middlewares/idem...
KeyIsFromCache) != nil } // WasPutToCache reports whether the middleware stored the response produced by // the current request in the cache. func WasPutToCache(c fiber.Ctx) bool { val := c.Locals(localsKeyWasPutToCache) if wasPut, ok := val.(bool); ok
localsKeyWasPutToCache ) const redactedKey = "[redacted]" // IsFromCache reports whether the middleware served the response from the // cache for the current request. func IsFromCache(c fiber.Ctx) bool { return c.Locals(locals
{ "filepath": "middleware/idempotency/idempotency.go", "language": "go", "file_size": 4868, "cut_index": 614, "middle_length": 229 }
potency import ( "sync" ) // Locker implements a spinlock for a string key. type Locker interface { Lock(key string) error Unlock(key string) error } type countedLock struct { mu sync.Mutex locked int } // MemoryLock coordinates access to idempotency keys using in-memory locks. // MemoryLock is safe for co...
return nil } // Unlock releases the lock associated with the provided key. func (l *MemoryLock) Unlock(key string) error { l.mu.Lock() lock, ok := l.keys[key] if !ok { // This happens if we try to unlock an unknown key l.mu.Unlock() return nil
ey string) error { l.mu.Lock() if l.keys == nil { l.keys = make(map[string]*countedLock) } lock, ok := l.keys[key] if !ok { lock = new(countedLock) l.keys[key] = lock } lock.locked++ l.mu.Unlock() lock.mu.Lock()
{ "filepath": "middleware/idempotency/locker.go", "language": "go", "file_size": 1480, "cut_index": 524, "middle_length": 229 }
der) (err error) { var field []byte _ = field var zb0001 uint32 zb0001, err = dc.ReadMapHeader() if err != nil { err = msgp.WrapError(err) return } for zb0001 > 0 { zb0001-- field, err = dc.ReadMapKeyPtr() if err != nil { err = msgp.WrapError(err) return } switch msgp.UnsafeString(field) { ...
dc.ReadString() if err != nil { err = msgp.WrapError(err, "Headers") return } var za0002 []string var zb0003 uint32 zb0003, err = dc.ReadArrayHeader() if err != nil { err = msgp.WrapError(err, "Headers", za0001)
eeded return } if z.Headers == nil { z.Headers = make(map[string][]string, zb0002) } else if len(z.Headers) > 0 { clear(z.Headers) } for zb0002 > 0 { zb0002-- var za0001 string za0001, err =
{ "filepath": "middleware/idempotency/response_msgp.go", "language": "go", "file_size": 6282, "cut_index": 716, "middle_length": 229 }
rt ( "context" "time" ) // stubLock implements Locker for testing purposes. type stubLock struct { lockErr error unlockErr error afterLock func() } func (s *stubLock) Lock(string) error { if s.afterLock != nil { s.afterLock() } return s.lockErr } func (s *stubLock) Unlock(string) error { return s.unlockEr...
// Call Get method to avoid code duplication return s.Get(key) } func (s *stubStorage) Set(key string, val []byte, _ time.Duration) error { if s.setErr != nil { return s.setErr } if s.data == nil { s.data = make(map[string][]byte) } s.data[key]
tring) ([]byte, error) { if s.getErr != nil { return nil, s.getErr } if s.data == nil { return nil, nil } return s.data[key], nil } func (s *stubStorage) GetWithContext(_ context.Context, key string) ([]byte, error) {
{ "filepath": "middleware/idempotency/stub_test.go", "language": "go", "file_size": 1771, "cut_index": 537, "middle_length": 229 }
.com/gofiber/fiber/v3" ) // Config defines the config for middleware. type Config struct { // FS is the file system to serve the static files from. // You can use interfaces compatible with fs.FS like embed.FS, os.DirFS etc. // // Optional. Default: nil FS fs.FS // Next defines a function to skip this middlewar...
// // Optional. Default: []string{"index.html"}. IndexNames []string `json:"index"` // Expiration duration for inactive file handlers. // Use a negative time.Duration to disable it. // // Optional. Default: 10 * time.Second. CacheDuration time.Dura
ModifyResponse fiber.Handler // NotFoundHandler defines a function to handle when the path is not found. // // Optional. Default: nil NotFoundHandler fiber.Handler // The names of the index files for serving a directory.
{ "filepath": "middleware/static/config.go", "language": "go", "file_size": 2413, "cut_index": 563, "middle_length": 229 }
ub.com/tinylib/msgp DO NOT EDIT. package csrf import ( "github.com/tinylib/msgp/msgp" ) // DecodeMsg implements msgp.Decodable func (z *item) DecodeMsg(dc *msgp.Reader) (err error) { var field []byte _ = field var zb0001 uint32 zb0001, err = dc.ReadMapHeader() if err != nil { err = msgp.WrapError(err) retu...
x80) if err != nil { return } return } // MarshalMsg implements msgp.Marshaler func (z item) MarshalMsg(b []byte) (o []byte, err error) { o = msgp.Require(b, z.Msgsize()) // map header, size 0 _ = z o = append(o, 0x80) return } // UnmarshalMsg
p() if err != nil { err = msgp.WrapError(err) return } } } return } // EncodeMsg implements msgp.Encodable func (z item) EncodeMsg(en *msgp.Writer) (err error) { // map header, size 0 _ = z err = en.Append(0
{ "filepath": "middleware/csrf/storage_manager_msgp.go", "language": "go", "file_size": 1721, "cut_index": 537, "middle_length": 229 }
fiber/fiber/v3/internal/storage/memory" ) var ErrInvalidIdempotencyKey = errors.New("invalid idempotency key") // Config defines the config for middleware. type Config struct { // Lock locks an idempotency key. // // Optional. Default: an in-memory locker for this process only. Lock Locker // Storage stores res...
Optional. Default: a function which ensures the header is 36 characters long (the size of an UUID). KeyHeaderValidate func(string) error // KeyHeader is the name of the header that contains the idempotency key. // // Optional. Default: X-Idempotency-K
true. // // Optional. Default: a function which skips the middleware on safe HTTP request method. Next func(c fiber.Ctx) bool // KeyHeaderValidate defines a function to validate the syntax of the idempotency header. // //
{ "filepath": "middleware/idempotency/config.go", "language": "go", "file_size": 3330, "cut_index": 614, "middle_length": 229 }
c/atomic" "testing" "time" "github.com/gofiber/fiber/v3/middleware/idempotency" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // go test -run Test_MemoryLock func Test_MemoryLock(t *testing.T) { t.Parallel() l := idempotency.NewMemoryLock() // Test that a lock can be acquired...
event goroutine leak { err := l.Unlock("a") require.NoError(t, err) } // Test lock and unlock sequence { err := l.Lock("b") require.NoError(t, err) } { err := l.Unlock("b") require.NoError(t, err) } { err := l.Lock("b") require.NoE
rr := l.Lock("a") assert.NoError(t, err) }() select { case <-done: t.Fatal("lock acquired again") case <-time.After(time.Second): // Expected: goroutine should still be blocked } } // Release lock "a" to pr
{ "filepath": "middleware/idempotency/locker_test.go", "language": "go", "file_size": 3016, "cut_index": 563, "middle_length": 229 }
rings "github.com/gofiber/utils/v2/strings" ) const ( schemeHTTP = "http" schemeHTTPS = "https" ) func compareTokens(a, b []byte) bool { return subtle.ConstantTimeCompare(a, b) == 1 } func compareStrings(a, b string) bool { return subtle.ConstantTimeCompare(utils.UnsafeBytes(a), utils.UnsafeBytes(b)) == 1 } fu...
heme, host string) string { host = utilsstrings.ToLower(host) defaultPort := "" switch scheme { case schemeHTTP: defaultPort = "80" case schemeHTTPS: defaultPort = "443" default: return host } parsedHost, err := url.Parse(scheme + "://" + h
normalizeSchemeHost(normalizedSchemeA, hostA) normalizedHostB := normalizeSchemeHost(normalizedSchemeB, hostB) return normalizedSchemeA == normalizedSchemeB && normalizedHostA == normalizedHostB } func normalizeSchemeHost(sc
{ "filepath": "middleware/csrf/helpers.go", "language": "go", "file_size": 3879, "cut_index": 614, "middle_length": 229 }
time" "github.com/gofiber/fiber/v3" "github.com/gofiber/fiber/v3/internal/memory" ) // msgp -file="storage_manager.go" -o="storage_manager_msgp.go" -tests=true -unexported // //go:generate msgp -o=storage_manager_msgp.go -tests=true -unexported type item struct{} const redactedKey = "[redacted]" //msgp:ignore man...
ageManager { // Create new storage handler storageManager := &storageManager{ pool: sync.Pool{ New: func() any { return new(item) }, }, shouldRedactKeys: shouldRedactKeys, } if storage != nil { // Use provided storage if provided st
//nolint:revive // Ignore unexported type storage fiber.Storage `msg:"-"` //nolint:revive // Ignore unexported type shouldRedactKeys bool } func newStorageManager(storage fiber.Storage, shouldRedactKeys bool) *stor
{ "filepath": "middleware/csrf/storage_manager.go", "language": "go", "file_size": 2537, "cut_index": 563, "middle_length": 229 }
EDIT. package idempotency import ( "bytes" "testing" "github.com/tinylib/msgp/msgp" ) func TestMarshalUnmarshalresponse(t *testing.T) { v := response{} bts, err := v.MarshalMsg(nil) if err != nil { t.Fatal(err) } left, err := v.UnmarshalMsg(bts) if err != nil { t.Fatal(err) } if len(left) > 0 { t....
esting.B) { v := response{} bts := make([]byte, 0, v.Msgsize()) bts, _ = v.MarshalMsg(bts[0:0]) b.SetBytes(int64(len(bts))) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { bts, _ = v.MarshalMsg(bts[0:0]) } } func BenchmarkUnmarshalres
er Skip(): %q", len(left), left) } } func BenchmarkMarshalMsgresponse(b *testing.B) { v := response{} b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { v.MarshalMsg(nil) } } func BenchmarkAppendMsgresponse(b *t
{ "filepath": "middleware/idempotency/response_msgp_test.go", "language": "go", "file_size": 2306, "cut_index": 563, "middle_length": 229 }
testing.T) { t.Parallel() app := fiber.New() app.Use(func(c fiber.Ctx) error { if err := c.Next(); err != nil { return err } isMethodSafe := fiber.IsMethodSafe(c.Method()) isIdempotent := IsFromCache(c) || WasPutToCache(c) hasReqHeader := c.Get("X-Idempotency-Key") != "" if isMethodSafe { if isI...
request header is not set") } } return nil }) // Needs to be at least a second as the memory storage doesn't support shorter durations. const lifetime = 2 * time.Second app.Use(New(Config{ Lifetime: lifetime, })) nextCount := func() fun
uest with unsafe HTTP method should be idempotent if X-Idempotency-Key request header is set") } } else if isIdempotent { return errors.New("request with unsafe HTTP method should not be idempotent if X-Idempotency-Key
{ "filepath": "middleware/idempotency/idempotency_test.go", "language": "go", "file_size": 13398, "cut_index": 921, "middle_length": 229 }
fiber.New() app.Use(New(Config{ Next: func(_ fiber.Ctx) bool { return true }, })) resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) } func Test_Middleware_BasicAuth(t *testing.T) { t.Parallel() a...
url string username string password string statusCode int }{ { url: "/testauth", statusCode: 200, username: "john", password: "doe", }, { url: "/testauth", statusCode: 200, username: "admin
ap[string]string{ "john": hashedJohn, "admin": string(hashedAdmin), }, })) app.Get("/testauth", func(c fiber.Ctx) error { username := UsernameFromContext(c) return c.SendString(username) }) tests := []struct {
{ "filepath": "middleware/basicauth/basicauth_test.go", "language": "go", "file_size": 21096, "cut_index": 1331, "middle_length": 229 }
gofiber/fiber/v3" ) // Config defines the config for the pagination middleware. type Config struct { // Next defines a function to skip this middleware when returned true. Next func(c fiber.Ctx) bool // PageKey is the query string key for page number. // // Optional. Default: "page" PageKey string // LimitKey...
query string key for offset. // // Optional. Default: "offset" OffsetKey string // CursorParam is an optional alias for the cursor query key. // // Optional. Default: "" CursorParam string // AllowedSorts is the list of allowed sort fields. //
tSort is the default sort field. // // Optional. Default: "id" DefaultSort string // CursorKey is the query string key for cursor-based pagination. // // Optional. Default: "cursor" CursorKey string // OffsetKey is the
{ "filepath": "middleware/paginate/config.go", "language": "go", "file_size": 2618, "cut_index": 563, "middle_length": 229 }
ithub.com/gofiber/utils/v2" ) // The contextKey type is unexported to prevent collisions with context keys defined in // other packages. type contextKey int const ( pageInfoKey contextKey = iota ) // DefaultMaxLimit is the default maximum limit allowed. const DefaultMaxLimit = 100 // maxCursorLen is the maximum al...
limit > cfg.MaxLimit { limit = cfg.MaxLimit } sorts := parseSortQuery(c.Query(cfg.SortKey), cfg.AllowedSorts, cfg.DefaultSort) cursorRaw := c.Query(cfg.CursorKey) if cursorRaw == "" && cfg.CursorParam != "" { cursorRaw = c.Query(cfg.Cursor
func(c fiber.Ctx) error { if cfg.Next != nil && cfg.Next(c) { return c.Next() } appCfg := c.App().Config() limit := fiber.Query(c, cfg.LimitKey, cfg.DefaultLimit) if limit < 1 { limit = cfg.DefaultLimit } if
{ "filepath": "middleware/paginate/paginate.go", "language": "go", "file_size": 3222, "cut_index": 614, "middle_length": 229 }
onfig defines the config for middleware. type Config struct { // Store is used to store the state of the middleware // // Default: an in memory store for this process only Storage fiber.Storage // LimiterMiddleware is the struct that implements a limiter middleware. // // Default: a new Fixed Window Rate Limite...
rate limiter entries // // Default: A function that returns the static `Expiration` value from the config. ExpirationFunc func(c fiber.Ctx) time.Duration // KeyGenerator allows you to generate custom keys, by default c.IP() is used // // Default: f
calculate the max requests supported by the rate limiter middleware // // Default: func(c fiber.Ctx) int { // return c.Max // } MaxFunc func(c fiber.Ctx) int // A function to dynamically calculate the expiration time for
{ "filepath": "middleware/limiter/config.go", "language": "go", "file_size": 3816, "cut_index": 614, "middle_length": 229 }
er/utils/v2" ) // FixedWindow implements a fixed-window rate limiting strategy. type FixedWindow struct{} // New creates a new fixed window middleware handler func (FixedWindow) New(cfg *Config) fiber.Handler { if cfg == nil { defaultCfg := configDefault() cfg = &defaultCfg } // Limiter variables mux := &syn...
ute middleware if Next returns true or if the max is 0 if (cfg.Next != nil && cfg.Next(c)) || maxRequests == 0 { return c.Next() } // Generate expiration from generator expirationDuration := cfg.ExpirationFunc(c) if expirationDuration <= 0 {
tTimeStampUpdater() // Return new handler return func(c fiber.Ctx) error { // Generate maxRequests from generator, if no generator was provided the default value returned is 5 maxRequests := cfg.MaxFunc(c) // Don't exec
{ "filepath": "middleware/limiter/limiter_fixed.go", "language": "go", "file_size": 3521, "cut_index": 614, "middle_length": 229 }
ter == "" { time.Sleep(500 * time.Millisecond) return } seconds, err := strconv.Atoi(retryAfter) require.NoError(t, err) delay := time.Duration(seconds) * time.Second // Sliding window needs roughly 2x the reported delay for the previous window to expire. if doubled := 2 * delay; doubled > delay { delay =...
ed: errors.Is(ctx.Err(), context.Canceled), } if value, ok := ctx.Value(markerKey).(string); ok { record.value = value } return record } func (s *contextRecorderLimiterStorage) GetWithContext(ctx context.Context, key string) ([]byte, error) { s.get
terStorage { return &contextRecorderLimiterStorage{failingLimiterStorage: newFailingLimiterStorage()} } func contextRecordFrom(ctx context.Context, key string) contextRecord { record := contextRecord{ key: key, cancel
{ "filepath": "middleware/limiter/limiter_test.go", "language": "go", "file_size": 49982, "cut_index": 2151, "middle_length": 229 }
"time" "github.com/gofiber/fiber/v3" "github.com/gofiber/fiber/v3/internal/memory" ) // msgp -file="manager.go" -o="manager_msgp.go" -tests=false -unexported // //go:generate msgp -o=manager_msgp.go -tests=false -unexported type item struct { currHits int prevHits int exp uint64 } //msgp:ignore manager t...
rage != nil { // Use provided storage if provided manager.storage = storage } else { // Fallback too memory storage manager.memory = memory.New() } return manager } // acquire returns an *entry from the sync.Pool func (m *manager) acquire() *it
torage fiber.Storage, shouldRedactKeys bool) *manager { // Create new storage handler manager := &manager{ pool: sync.Pool{ New: func() any { return new(item) }, }, shouldRedactKeys: shouldRedactKeys, } if sto
{ "filepath": "middleware/limiter/manager.go", "language": "go", "file_size": 2736, "cut_index": 563, "middle_length": 229 }
ime" "github.com/gofiber/fiber/v3" ) // Handler writes events to a single SSE stream. type Handler func(c fiber.Ctx, stream *Stream) error // Config defines the config for the SSE handler. type Config struct { // Handler writes events to the stream. // // Required. Handler Handler // OnClose is called after t...
tect disconnected clients. // When DisableHeartbeat is false, values less than or equal to zero are // replaced by the default interval. // // Optional. Default: 15 * time.Second HeartbeatInterval time.Duration // DisableHeartbeat disables automatic
less than or equal to zero disable the initial retry field. // // Optional. Default: 0 Retry time.Duration // HeartbeatInterval controls comment heartbeats used to keep intermediaries // from closing idle streams and to de
{ "filepath": "middleware/sse/config.go", "language": "go", "file_size": 1599, "cut_index": 537, "middle_length": 229 }
m/gofiber/utils/v2" "golang.org/x/crypto/bcrypt" ) var ErrInvalidSHA256PasswordLength = errors.New("decode SHA256 password: invalid length") // fallbackDummySHA512 is SHA-512("fiber-basicauth-dummy"), used as a // constant-time comparison target when no users are configured. var fallbackDummySHA512 = [sha512.Size]by...
(string) bool type userVerifiers map[string]passwordVerifier // Verifier strengths are ordered by expected verification work: // bcrypt is strongest because it is adaptive and cost-based, SHA-512 follows // as the larger fixed-cost digest, and SHA-256 is
0x24, 0x1e, 0xa6, 0x1f, 0x2a, 0x11, 0x97, 0xb1, 0xb9, 0x67, 0xa9, 0xf7, 0x3b, 0x82, 0x8f, 0x95, 0xf5, 0x58, 0xed, 0x3c, 0xab, 0x43, 0x22, 0xf6, 0xfa, 0x84, 0x1d, 0xbc, 0xeb, 0x87, 0xc4, 0x1c, 0x5a, } type passwordVerifier func
{ "filepath": "middleware/basicauth/config.go", "language": "go", "file_size": 8915, "cut_index": 716, "middle_length": 229 }
figDefault(t *testing.T) { t.Parallel() cfg := configDefault() require.Equal(t, "page", cfg.PageKey) require.Equal(t, 1, cfg.DefaultPage) require.Equal(t, "limit", cfg.LimitKey) require.Equal(t, 10, cfg.DefaultLimit) require.Equal(t, DefaultMaxLimit, cfg.MaxLimit) } func Test_ConfigOverride(t *testing.T) { t....
est_ConfigOverrideCursorKey(t *testing.T) { t.Parallel() cfg := configDefault(Config{ CursorKey: "after", CursorParam: "starting_after", }) require.Equal(t, "after", cfg.CursorKey) require.Equal(t, "starting_after", cfg.CursorParam) } func Tes
mitKey) require.Equal(t, 5, cfg.DefaultPage) require.Equal(t, 50, cfg.DefaultLimit) } func Test_ConfigDefaultCursorKey(t *testing.T) { t.Parallel() cfg := configDefault() require.Equal(t, "cursor", cfg.CursorKey) } func T
{ "filepath": "middleware/paginate/paginate_test.go", "language": "go", "file_size": 31202, "cut_index": 1331, "middle_length": 229 }
type SlidingWindow struct{} // New creates a new sliding window middleware handler func (SlidingWindow) New(cfg *Config) fiber.Handler { if cfg == nil { defaultCfg := configDefault() cfg = &defaultCfg } // Limiter variables mux := &sync.RWMutex{} // Create manager to simplify storage operations ( see manag...
il && cfg.Next(c)) || maxRequests == 0 { return c.Next() } // Generate expiration from generator expirationDuration := cfg.ExpirationFunc(c) if expirationDuration <= 0 { expirationDuration = ConfigDefault.Expiration } expiration := uint6
r { // Generate maxRequests from generator, if no generator was provided the default value returned is 5 maxRequests := cfg.MaxFunc(c) // Don't execute middleware if Next returns true or if the max is 0 if (cfg.Next != n
{ "filepath": "middleware/limiter/limiter_sliding.go", "language": "go", "file_size": 6188, "cut_index": 716, "middle_length": 229 }
nylib/msgp DO NOT EDIT. import ( "bytes" "testing" "github.com/tinylib/msgp/msgp" ) func TestMarshalUnmarshalitem(t *testing.T) { v := item{} bts, err := v.MarshalMsg(nil) if err != nil { t.Fatal(err) } left, err := v.UnmarshalMsg(bts) if err != nil { t.Fatal(err) } if len(left) > 0 { t.Errorf("%d b...
sgsize()) bts, _ = v.MarshalMsg(bts[0:0]) b.SetBytes(int64(len(bts))) b.ReportAllocs() for b.Loop() { bts, _ = v.MarshalMsg(bts[0:0]) } } func BenchmarkUnmarshalitem(b *testing.B) { v := item{} bts, _ := v.MarshalMsg(nil) b.ReportAllocs() b.Set
q", len(left), left) } } func BenchmarkMarshalMsgitem(b *testing.B) { v := item{} b.ReportAllocs() for b.Loop() { v.MarshalMsg(nil) } } func BenchmarkAppendMsgitem(b *testing.B) { v := item{} bts := make([]byte, 0, v.M
{ "filepath": "middleware/limiter/manager_msgp_test.go", "language": "go", "file_size": 2098, "cut_index": 563, "middle_length": 229 }
kage limiter import ( "errors" "github.com/gofiber/fiber/v3" ) const ( // X-RateLimit-* headers xRateLimitLimit = "X-RateLimit-Limit" xRateLimitRemaining = "X-RateLimit-Remaining" xRateLimitReset = "X-RateLimit-Reset" ) // Handler defines a rate-limiting strategy that can produce a middleware // handl...
onse status func getEffectiveStatusCode(c fiber.Ctx, err error) int { // If there's an error and it's a *fiber.Error, use its status code if err != nil { var fiberErr *fiber.Error if errors.As(err, &fiberErr) { return fiberErr.Code } } // Oth
efault config cfg := configDefault(config...) // Return the specified middleware handler. return cfg.LimiterMiddleware.New(&cfg) } // getEffectiveStatusCode returns the actual status code, considering both the error and resp
{ "filepath": "middleware/limiter/limiter.go", "language": "go", "file_size": 1073, "cut_index": 515, "middle_length": 229 }
" "github.com/gofiber/utils/v2" ) var errInvalidField = errors.New("field must not contain CR or LF") // Event defines a single Server-Sent Event frame. type Event struct { // Data is written as one or more data fields. Strings and byte slices are // written as-is; other values are JSON encoded. Data any // ID...
ield(event.ID) if err != nil { return fmt.Errorf("sse: invalid id: %w", err) } if id != "" { appendField(&frame, "id", id) } } if event.Name != "" { name, err := sanitizeField(event.Name) if err != nil { return fmt.Errorf("sse: inval
event Event, jsonMarshal ...utils.JSONMarshal) error { data, err := eventData(event.Data, jsonMarshalOrDefault(jsonMarshal)) if err != nil { return err } var frame bytes.Buffer if event.ID != "" { id, err := sanitizeF
{ "filepath": "middleware/sse/event.go", "language": "go", "file_size": 4432, "cut_index": 614, "middle_length": 229 }
rallel() var buf bytes.Buffer w := bufio.NewWriter(&buf) require.NoError(t, writeEvent(w, Event{ ID: " 42 ", Name: "update", Data: "one\r\ntwo", Retry: 2500 * time.Millisecond, })) require.NoError(t, w.Flush()) require.Equal(t, "id: 42\nevent: update\nretry: 2500\ndata: one\ndata: two\n\n", buf.St...
", Name: " ", Data: "ok", })) require.NoError(t, w.Flush()) require.Equal(t, "data: ok\n\n", buf.String()) } func Test_SSE_EventJSONEncodesData(t *testing.T) { t.Parallel() var buf bytes.Buffer w := bufio.NewWriter(&buf) require.NoError(
y: 1", Data: "ignored", }), errInvalidField) } func Test_SSE_EventOmitsWhitespaceOnlyFields(t *testing.T) { t.Parallel() var buf bytes.Buffer w := bufio.NewWriter(&buf) require.NoError(t, writeEvent(w, Event{ ID: "
{ "filepath": "middleware/sse/sse_test.go", "language": "go", "file_size": 14983, "cut_index": 921, "middle_length": 229 }
"net/http/httptest" "testing" "github.com/gofiber/fiber/v3" "github.com/stretchr/testify/require" ) func Test_Non_Expvar_Path(t *testing.T) { t.Parallel() app := fiber.New() app.Use(New()) app.Get("/", func(c fiber.Ctx) error { return c.SendString("escaped") }) resp, err := app.Test(httptest.NewReques...
r.MethodGet, "/debug/vars", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) require.Equal(t, fiber.MIMEApplicationJSONCharsetUTF8, resp.Header.Get(fiber.HeaderContentType)) b, err := io.ReadAll(resp.Body) require.NoError(
tring(b)) } func Test_Expvar_Index(t *testing.T) { t.Parallel() app := fiber.New() app.Use(New()) app.Get("/", func(c fiber.Ctx) error { return c.SendString("escaped") }) resp, err := app.Test(httptest.NewRequest(fibe
{ "filepath": "middleware/expvar/expvar_test.go", "language": "go", "file_size": 2464, "cut_index": 563, "middle_length": 229 }
un Test_Middleware_Favicon func Test_Middleware_Favicon(t *testing.T) { t.Parallel() app := fiber.New() app.Use(New()) app.Get("/", func(_ fiber.Ctx) error { return nil }) // Skip Favicon middleware resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err, "app.T...
quire.Equal(t, fiber.StatusOK, resp.StatusCode, "Status code") resp, err = app.Test(httptest.NewRequest(fiber.MethodPut, "/favicon.ico", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, fiber.StatusMethodNotAllowed, resp.StatusCo
"app.Test(req)") require.Equal(t, fiber.StatusNoContent, resp.StatusCode, "Status code") resp, err = app.Test(httptest.NewRequest(fiber.MethodOptions, "/favicon.ico", http.NoBody)) require.NoError(t, err, "app.Test(req)") re
{ "filepath": "middleware/favicon/favicon_test.go", "language": "go", "file_size": 6397, "cut_index": 716, "middle_length": 229 }
Missing query token, err = FromQuery("token").Extract(ctx) require.Empty(t, token) require.ErrorIs(t, err, ErrNotFound) // Missing header token, err = FromHeader("X-Token").Extract(ctx) require.Empty(t, token) require.ErrorIs(t, err, ErrNotFound) // Missing Auth header token, err = FromAuthHeader("Bearer").E...
err != nil { panic(err) } return req } // go test -run Test_Extractors func Test_Extractors(t *testing.T) { t.Parallel() t.Run("FromParam", func(t *testing.T) { t.Parallel() app := fiber.New() app.Get("/test/:token", func(c fiber.Ctx) error
ErrNotFound) } // newRequest creates a new *http.Request for Fiber's app.Test func newRequest(method, target string) *http.Request { req, err := http.NewRequestWithContext(context.Background(), method, target, http.NoBody) if
{ "filepath": "extractors/extractors_test.go", "language": "go", "file_size": 29106, "cut_index": 1331, "middle_length": 229 }
m(_ io.Reader) (int64, error) { return 0, errContextTestWrite } func (failingContextBuffer) WriteTo(_ io.Writer) (int64, error) { return 0, errContextTestWrite } func (failingContextBuffer) Bytes() []byte { return nil } func (failingContextBuffer) Write(_ []byte) (int, error) { return 0, errCon...
mplate compiles a context template using the package-default tag // map merged with the supplied custom tags. It mirrors the production merge // performed by SetContextTemplate so test expectations stay aligned. func buildTestTemplate(t *testing.T, format
estWrite } func (failingContextBuffer) Set([]byte) {} func (failingContextBuffer) SetString(string) {} func (failingContextBuffer) String() string { return "" } // buildTestTe
{ "filepath": "log/context_test.go", "language": "go", "file_size": 13034, "cut_index": 921, "middle_length": 229 }
at w contains exactly two log lines, the first // emitted from withContextLine and the second from infoLine, both annotated // with default_test.go via the standard library's Lshortfile flag. func expectCallerOutput(t *testing.T, w *byteSliceWriter, withContextLine, infoLine int) { t.Helper() want := fmt.Sprintf("def...
ing.T) { t.Cleanup(initDefaultLogger) logger = &defaultLogger{ stdlog: log.New(os.Stderr, "", log.Lshortfile), depth: 4, } var w byteSliceWriter SetOutput(&w) ctx := context.TODO() withContextLine := callSiteLine(t) + 1 WithContext(ctx).Inf
he bare Info call site (line %d)", withContextLine, infoLine) } // Test_WithContextCaller runs serially because it mutates the package-global // logger and output to verify caller attribution. func Test_WithContextCaller(t *test
{ "filepath": "log/default_test.go", "language": "go", "file_size": 17813, "cut_index": 1331, "middle_length": 229 }
aultSystemLogger(t *testing.T) { t.Parallel() defaultL := DefaultLogger[*log.Logger]() require.Equal(t, logger, defaultL) } func Test_SetLogger(t *testing.T) { setLog := &defaultLogger{ stdlog: log.New(os.Stderr, "", log.LstdFlags|log.Lshortfile|log.Lmicroseconds), depth: 6, } SetLogger(setLog) require.Eq...
3", level: LevelWarn, expected: LevelWarn, }, { name: "Test case 4", level: LevelError, expected: LevelError, }, { name: "Test case 5", level: LevelFatal, expected: LevelFatal, }, } // Run tests for _
Level expected Level }{ { name: "Test case 1", level: LevelDebug, expected: LevelDebug, }, { name: "Test case 2", level: LevelInfo, expected: LevelInfo, }, { name: "Test case
{ "filepath": "log/fiberlog_test.go", "language": "go", "file_size": 3752, "cut_index": 614, "middle_length": 229 }
( bindingURI = "uri" bindingForm = "form" bindingQuery = "query" bindingHeader = "header" bindingRespHeader = "respHeader" bindingCookie = "cookie" ) // Binder errors var ( ErrSuitableContentNotFound = errors.New("binder: suitable content not found to parse body") ErrMapNotConvertibl...
erBinderPool = sync.Pool{ New: func() any { return &HeaderBinding{} }, } var RespHeaderBinderPool = sync.Pool{ New: func() any { return &RespHeaderBinding{} }, } var CookieBinderPool = sync.Pool{ New: func() any { return &CookieBinding{} }, }
lized") ErrInvalidDestinationValue = errors.New("binder: invalid destination value") ErrUnmatchedBrackets = errors.New("unmatched brackets") ) var errPoolTypeAssertion = errors.New("failed to type-assert to T") var Head
{ "filepath": "binder/binder.go", "language": "go", "file_size": 2041, "cut_index": 563, "middle_length": 229 }
lib/msgp/msgp" ) // DecodeMsg implements msgp.Decodable func (z *item) DecodeMsg(dc *msgp.Reader) (err error) { var field []byte _ = field var zb0001 uint32 zb0001, err = dc.ReadMapHeader() if err != nil { err = msgp.WrapError(err) return } for zb0001 > 0 { zb0001-- field, err = dc.ReadMapKeyPtr() if ...
err = msgp.WrapError(err, "exp") return } default: err = dc.Skip() if err != nil { err = msgp.WrapError(err) return } } } return } // EncodeMsg implements msgp.Encodable func (z item) EncodeMsg(en *msgp.Writer) (err error) {
, "currHits") return } case "prevHits": z.prevHits, err = dc.ReadInt() if err != nil { err = msgp.WrapError(err, "prevHits") return } case "exp": z.exp, err = dc.ReadUint64() if err != nil {
{ "filepath": "middleware/limiter/manager_msgp.go", "language": "go", "file_size": 3472, "cut_index": 614, "middle_length": 229 }
"io/fs" "github.com/gofiber/fiber/v3" ) // Config defines the config for middleware. type Config struct { // FileSystem is an optional alternate filesystem to search for the favicon in. // An example of this could be an embedded or network filesystem // // Optional. Default: nil FileSystem fs.FS `json:"-"` ...
should be set // // Optional. Default: "public, max-age=31536000" CacheControl string `json:"cache_control"` // Raw data of the favicon file // // Optional. Default: nil Data []byte `json:"-"` // MaxBytes limits the maximum size of the cached fav
ched // // Optional. Default: "" File string `json:"file"` // URL for favicon handler // // Optional. Default: "/favicon.ico" URL string `json:"url"` // CacheControl defines how the Cache-Control header in the response
{ "filepath": "middleware/favicon/config.go", "language": "go", "file_size": 1752, "cut_index": 537, "middle_length": 229 }
s" "strconv" "github.com/gofiber/fiber/v3" ) const ( fPath = "/favicon.ico" hType = "image/x-icon" hAllow = "GET, HEAD, OPTIONS" hZero = "0" ) // New creates a new middleware handler func New(config ...Config) fiber.Handler { cfg := configDefault(config...) // Load iconData if provided var ( err ...
panic(err) } defer func() { _ = f.Close() //nolint:errcheck // not needed }() if iconData, err = readLimited(f, cfg.MaxBytes); err != nil { panic(err) } } else { f, err = os.Open(cfg.File) if err != nil { panic(err)
Header = strconv.Itoa(len(cfg.Data)) iconLen = len(cfg.Data) } else if cfg.File != "" { // read from configured filesystem if present if cfg.FileSystem != nil { f, err = cfg.FileSystem.Open(cfg.File) if err != nil {
{ "filepath": "middleware/favicon/favicon.go", "language": "go", "file_size": 2557, "cut_index": 563, "middle_length": 229 }
parametric. Registering a tag named "value:" via RegisterContextTag is rejected — the // renderer is reserved for context-value lookups. const TagContextValue = "value:" // Tag names registered by Fiber's built-in middlewares. Treat them as the // canonical identifiers for the values produced by requestid, basicauth,...
logger. DefaultFormat = "" // RequestIDFormat renders the request ID registered by the requestid middleware. RequestIDFormat = "[${" + TagRequestID + "}] " // KeyValueFormat renders commonly registered middleware context values as // key/value fields
DDashed = "request-id" TagUsername = "username" TagAPIKey = "api-key" TagCSRFToken = "csrf-token" TagSessionID = "session-id" ) const ( // DefaultFormat disables contextual fields for the default
{ "filepath": "log/context.go", "language": "go", "file_size": 9402, "cut_index": 921, "middle_length": 229 }
unc Fatal(v ...any) { logger.Fatal(v...) } // Error calls the default logger's Error method. func Error(v ...any) { logger.Error(v...) } // Warn calls the default logger's Warn method. func Warn(v ...any) { logger.Warn(v...) } // Info calls the default logger's Info method. func Info(v ...any) { logger.Info(v......
rmat, v...) } // Errorf calls the default logger's Errorf method. func Errorf(format string, v ...any) { logger.Errorf(format, v...) } // Warnf calls the default logger's Warnf method. func Warnf(format string, v ...any) { logger.Warnf(format, v...) }
) } // Panic calls the default logger's Panic method. func Panic(v ...any) { logger.Panic(v...) } // Fatalf calls the default logger's Fatalf method and then os.Exit(1). func Fatalf(format string, v ...any) { logger.Fatalf(fo
{ "filepath": "log/fiberlog.go", "language": "go", "file_size": 3896, "cut_index": 614, "middle_length": 229 }
rsorEncode = errors.New("paginate: failed to encode cursor values") // SortOrder represents sort order. type SortOrder string const ( ASC SortOrder = "asc" DESC SortOrder = "desc" ) // SortField represents a sort field with direction. type SortField struct { Field string `json:"field"` Order SortOrder `json:...
NextCursor string `json:"next_cursor,omitempty"` Sort []SortField `json:"sort"` Page int `json:"page"` Limit int `json:"limit"` Offset int `json:"offset"` HasMore bool `json
n ASC } // PageInfo contains pagination information. type PageInfo struct { cursorData map[string]any jsonMarshal utils.JSONMarshal jsonUnmarshal utils.JSONUnmarshal Cursor string `json:"cursor,omitempty"`
{ "filepath": "middleware/paginate/page_info.go", "language": "go", "file_size": 5322, "cut_index": 716, "middle_length": 229 }
ue. The value may be fiber.Ctx, // *fasthttp.RequestCtx, context.Context, or another value understood by // ContextTagFunc implementations. type retainedContext struct { value any isOk bool } // newRetainedContext wraps value, treating both untyped nil and typed-nil // pointers/interfaces/maps/slices/channels/funcs...
edContext { if value == nil { return retainedContext{} } switch rv := reflect.ValueOf(value); rv.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice: if rv.IsNil() { return retainedContext{}
r; passing it through to a tag renderer would cause the renderer // to dereference a nil receiver. Reflection here is one-shot per WithContext // call — far off the per-log-line hot path. func newRetainedContext(value any) retain
{ "filepath": "log/default.go", "language": "go", "file_size": 9925, "cut_index": 921, "middle_length": 229 }
// baseLogger defines the minimal logger functionality required by the package. // It allows storing any logger implementation regardless of its generic type. type baseLogger interface { CommonLogger SetLevel(Level) SetOutput(io.Writer) WithContext(ctx any) CommonLogger } var logger baseLogger = &defaultLogger{ s...
(format string, v ...any) Debugf(format string, v ...any) Infof(format string, v ...any) Warnf(format string, v ...any) Errorf(format string, v ...any) Fatalf(format string, v ...any) Panicf(format string, v ...any) } // WithLogger is a logger inter
{ Trace(v ...any) Debug(v ...any) Info(v ...any) Warn(v ...any) Error(v ...any) Fatal(v ...any) Panic(v ...any) } // FormatLogger is a logger interface that output logs with a format. type FormatLogger interface { Tracef
{ "filepath": "log/log.go", "language": "go", "file_size": 2909, "cut_index": 563, "middle_length": 229 }
/ Example usage: // // import "github.com/gofiber/fiber/v3/extractors" // // // Extract from Authorization header // authExtractor := extractors.FromAuthHeader("Bearer") // // // Chain multiple sources with fallback // tokenExtractor := extractors.Chain( // extractors.FromHeader("X-API-Key"), // extractors.From...
e from which an API key is extracted. // This is informational metadata that helps developers understand the extractor behavior. type Source int const ( // SourceHeader indicates the value is extracted from an HTTP header. SourceHeader Source = iota /
tracted values in transit // - Consider source-specific security policies for your use case import ( "errors" "net/url" "github.com/gofiber/fiber/v3" "github.com/gofiber/utils/v2" ) // Source represents the type of sourc
{ "filepath": "extractors/extractors.go", "language": "go", "file_size": 17140, "cut_index": 921, "middle_length": 229 }
xamacker/cbor/v2" "github.com/stretchr/testify/require" ) func Test_CBORBinder_Bind(t *testing.T) { t.Parallel() b := &CBORBinding{ CBORDecoder: cbor.Unmarshal, } require.Equal(t, "cbor", b.Name()) type Post struct { Title string `cbor:"title"` } type User struct { Name string `cbor:"name"` Posts...
t, "john", user.Name) require.Equal(t, 42, user.Age) require.Len(t, user.Posts, 3) require.Equal(t, "post1", user.Posts[0].Title) require.Equal(t, "post2", user.Posts[1].Title) require.Equal(t, "post3", user.Posts[2].Title) require.Contains(t, user.N
e: 42, Posts: []Post{ {Title: "post1"}, {Title: "post2"}, {Title: "post3"}, }, } body, err := cbor.Marshal(wantedUser) require.NoError(t, err) err = b.Bind(body, &user) require.NoError(t, err) require.Equal(
{ "filepath": "binder/cbor_test.go", "language": "go", "file_size": 2036, "cut_index": 563, "middle_length": 229 }
tretchr/testify/require" "github.com/valyala/fasthttp" ) func Test_CookieBinder_Bind(t *testing.T) { t.Parallel() b := &CookieBinding{ EnableSplitting: true, } require.Equal(t, "cookie", b.Name()) type Post struct { Title string `form:"title"` } type User struct { Name string `form:"name"` Names ...
42, user.Age) require.Contains(t, user.Names, "john") require.Contains(t, user.Names, "doe") b.Reset() require.False(t, b.EnableSplitting) } func Benchmark_CookieBinder_Bind(b *testing.B) { b.ReportAllocs() binder := &CookieBinding{ EnableSplitt
tCookie("names", "john,doe") req.Header.SetCookie("age", "42") t.Cleanup(func() { fasthttp.ReleaseRequest(req) }) err := b.Bind(req, &user) require.NoError(t, err) require.Equal(t, "john", user.Name) require.Equal(t,
{ "filepath": "binder/cookie_test.go", "language": "go", "file_size": 2054, "cut_index": 563, "middle_length": 229 }
:"name"` Names []string `form:"names"` Posts []Post `form:"posts"` Age int `form:"age"` } var user User req := fasthttp.AcquireRequest() req.SetBodyString("name=john&names=john,doe&age=42&posts[0][title]=post1&posts[1][title]=post2&posts[2][title]=post3") req.Header.SetContentType("application/x-ww...
re.Contains(t, user.Names, "doe") b.Reset() require.False(t, b.EnableSplitting) } func Test_FormBinder_Bind_ParseError(t *testing.T) { b := &FormBinding{} type User struct { Age int `form:"age"` } var user User req := fasthttp.AcquireRequest()
r.Age) require.Len(t, user.Posts, 3) require.Equal(t, "post1", user.Posts[0].Title) require.Equal(t, "post2", user.Posts[1].Title) require.Equal(t, "post3", user.Posts[2].Title) require.Contains(t, user.Names, "john") requi
{ "filepath": "binder/form_test.go", "language": "go", "file_size": 14792, "cut_index": 921, "middle_length": 229 }
mport ( "github.com/gofiber/utils/v2" "github.com/valyala/fasthttp" ) // HeaderBinding is the binder implementation used to populate values from HTTP headers. type HeaderBinding struct { EnableSplitting bool } // Name returns the binding name. func (*HeaderBinding) Name() string { return bindingHeader } // Bind ...
feString(val) if err := formatBindData(b.Name(), out, data, k, v, b.EnableSplitting, false); err != nil { return err } } return parse(b.Name(), out, data) } // Reset resets the HeaderBinding binder. func (b *HeaderBinding) Reset() { b.EnableSpl
) { k := utils.UnsafeString(key) v := utils.Unsa
{ "filepath": "binder/header.go", "language": "go", "file_size": 854, "cut_index": 529, "middle_length": 52 }
" "github.com/stretchr/testify/require" ) func Test_JSON_Binding_Bind(t *testing.T) { t.Parallel() b := &JSONBinding{ JSONDecoder: json.Unmarshal, } require.Equal(t, "json", b.Name()) type Post struct { Title string `json:"title"` } type User struct { Name string `json:"name"` Posts []Post `json:"...
3", user.Posts[2].Title) b.Reset() require.Nil(t, b.JSONDecoder) } func Test_JSON_Binding_Bind_OptionalIDParam(t *testing.T) { t.Parallel() b := &JSONBinding{ JSONDecoder: json.Unmarshal, } // Use case from original issue type OptionalIDParam
r(t, err) require.Equal(t, "john", user.Name) require.Equal(t, 42, user.Age) require.Len(t, user.Posts, 3) require.Equal(t, "post1", user.Posts[0].Title) require.Equal(t, "post2", user.Posts[1].Title) require.Equal(t, "post
{ "filepath": "binder/json_test.go", "language": "go", "file_size": 2596, "cut_index": 563, "middle_length": 229 }
der import ( "github.com/gofiber/utils/v2" "github.com/valyala/fasthttp" ) // CookieBinding is the cookie binder for cookie request body. type CookieBinding struct { EnableSplitting bool } // Name returns the binding name. func (*CookieBinding) Name() string { return bindingCookie } // Bind parses the request c...
if err := formatBindData(b.Name(), out, data, k, v, b.EnableSplitting, false); err != nil { return err } } return parse(b.Name(), out, data) } // Reset resets the CookieBinding binder. func (b *CookieBinding) Reset() { b.EnableSplitting = false
s.UnsafeString(key) v := utils.UnsafeString(val)
{ "filepath": "binder/cookie.go", "language": "go", "file_size": 833, "cut_index": 523, "middle_length": 52 }
tretchr/testify/require" "github.com/valyala/fasthttp" ) func Test_HeaderBinder_Bind(t *testing.T) { t.Parallel() b := &HeaderBinding{ EnableSplitting: true, } require.Equal(t, "header", b.Name()) type User struct { Name string `header:"Name"` Names []string `header:"Names"` Posts []string `header:"...
ire.Len(t, user.Posts, 3) require.Equal(t, "post1", user.Posts[0]) require.Equal(t, "post2", user.Posts[1]) require.Equal(t, "post3", user.Posts[2]) require.Contains(t, user.Names, "john") require.Contains(t, user.Names, "doe") b.Reset() require.Fa
req.Header.Set("posts", "post1,post2,post3") t.Cleanup(func() { fasthttp.ReleaseRequest(req) }) err := b.Bind(req, &user) require.NoError(t, err) require.Equal(t, "john", user.Name) require.Equal(t, 42, user.Age) requ
{ "filepath": "binder/header_test.go", "language": "go", "file_size": 2171, "cut_index": 563, "middle_length": 229 }
ntext" "errors" "fmt" "net" "strconv" "strings" "sync" "github.com/valyala/fasthttp" "github.com/gofiber/fiber/v3" "github.com/gofiber/fiber/v3/addon/retry" ) const boundary = "FiberFormBoundary" // RequestHook is a function invoked before the request is sent. // It receives a Client and a Request, allowin...
don/retry` package. type RetryConfig = retry.Config // addMissingPort appends the appropriate port number to the given address if it doesn't have one. // If isTLS is true, it uses port 443; otherwise, it uses port 80. func addMissingPort(addr string, isTL
e, and Request, allowing you to modify the Response data // or perform actions based on the response. type ResponseHook func(*Client, *Response, *Request) error // RetryConfig is an alias for the `retry.Config` type from the `ad
{ "filepath": "client/core.go", "language": "go", "file_size": 8574, "cut_index": 716, "middle_length": 229 }
x509/pkix" "encoding/pem" "errors" "fmt" "math/big" "net" "time" ) var errAppendCACert = errors.New("failed to append CA certificate to certificate pool") // GetTLSConfigs generates TLS configurations for a test server and client that // trust each other using an in-memory certificate authority. func GetTLSConf...
tring{"Amsterdam"}, StreetAddress: []string{"Huidenstraat"}, PostalCode: []string{"1011 AA"}, }, NotBefore: time.Now(), NotAfter: time.Now().AddDate(10, 0, 0), IsCA: true, ExtKeyUsage:
up our CA certificate ca := &x509.Certificate{ SerialNumber: big.NewInt(2021), Subject: pkix.Name{ Organization: []string{"Fiber"}, Country: []string{"NL"}, Province: []string{""}, Locality: []s
{ "filepath": "internal/tlstest/tls.go", "language": "go", "file_size": 4124, "cut_index": 614, "middle_length": 229 }
e binder import ( "errors" "github.com/gofiber/utils/v2" ) var ErrMsgPackNotConfigured = errors.New("binder: msgpack is not configured, please check docs: https://docs.gofiber.io/next/guide/advance-format#msgpack") // MsgPackBinding is the MsgPack binder for MsgPack request body. type MsgPackBinding struct { Msg...
gpackMarshal returns an error to signal that a MsgPack marshaler must // be configured before MsgPack support can be used. func UnimplementedMsgpackMarshal(_ any) ([]byte, error) { return nil, ErrMsgPackNotConfigured } // UnimplementedMsgpackUnmarshal re
esult. func (b *MsgPackBinding) Bind(body []byte, out any) error { return b.MsgPackDecoder(body, out) } // Reset resets the MsgPackBinding binder. func (b *MsgPackBinding) Reset() { b.MsgPackDecoder = nil } // UnimplementedMs
{ "filepath": "binder/msgpack.go", "language": "go", "file_size": 1207, "cut_index": 518, "middle_length": 229 }
ng: true, } require.Equal(t, "query", b.Name()) type Post struct { Title string `query:"title"` } type User struct { Name string `query:"name"` Names []string `query:"names"` Posts []Post `query:"posts"` Age int `query:"age"` } var user User req := fasthttp.AcquireRequest() req.URI().S...
require.Equal(t, "post3", user.Posts[2].Title) require.Contains(t, user.Names, "john") require.Contains(t, user.Names, "doe") b.Reset() require.False(t, b.EnableSplitting) } func Benchmark_QueryBinder_Bind(b *testing.B) { b.ReportAllocs() binder
&user) require.NoError(t, err) require.Equal(t, "john", user.Name) require.Equal(t, 42, user.Age) require.Len(t, user.Posts, 3) require.Equal(t, "post1", user.Posts[0].Title) require.Equal(t, "post2", user.Posts[1].Title)
{ "filepath": "binder/query_test.go", "language": "go", "file_size": 6188, "cut_index": 716, "middle_length": 229 }
"github.com/gofiber/utils/v2" "github.com/valyala/fasthttp" ) const MIMEMultipartForm string = "multipart/form-data" var ( formMapPool = sync.Pool{ New: func() any { return make(map[string][]string) }, } formFileMapPool = sync.Pool{ New: func() any { return make(map[string][]*multipart.FileHeader) ...
.ContentType())) == MIMEMultipartForm { return b.bindMultipart(req, out) } data := acquireFormMap() defer releaseFormMap(data) for key, val := range req.PostArgs().All() { k := utils.UnsafeString(key) v := utils.UnsafeString(val) if err := fo
Name() string { return "form" } // Bind parses the request body and returns the result. func (b *FormBinding) Bind(req *fasthttp.Request, out any) error { // Handle multipart form if FilterFlags(utils.UnsafeString(req.Header
{ "filepath": "binder/form.go", "language": "go", "file_size": 2749, "cut_index": 563, "middle_length": 229 }
ar dummy2 struct{ f string } require.False(t, equalFieldType(&dummy2, reflect.String, "f", "query")) var user struct { Name string Address string `query:"address"` Age int `query:"AGE"` } require.True(t, equalFieldType(&user, reflect.String, "name", "query")) require.True(t, equalFieldType(&user, ...
int `query:"AGE"` } `query:"user"` } require.True(t, equalFieldType(&user2, reflect.String, "user.name", "query")) require.True(t, equalFieldType(&user2, reflect.String, "user.Name", "query")) require.True(t, equalFieldType(&user2, reflect.S
re.True(t, equalFieldType(&user, reflect.Int, "AGE", "query")) require.True(t, equalFieldType(&user, reflect.Int, "age", "query")) var user2 struct { User struct { Name string Address string `query:"address"` Age
{ "filepath": "binder/mapping_test.go", "language": "go", "file_size": 14757, "cut_index": 921, "middle_length": 229 }
rserType require two element, type and converter for register. // Use ParserType with BodyParser for parsing custom type in form data. type ParserType struct { CustomType any Converter func(string) reflect.Value } var ( decoderPoolMu sync.RWMutex // decoderPoolMap helps to improve binders decoderPoolMap = map[st...
} // SetParserDecoder allow globally change the option of form decoder, update decoderPool func SetParserDecoder(parserConfig ParserConfig) { decoderPoolMu.Lock() defer decoderPoolMu.Unlock() for _, tag := range tags { decoderPoolMap[tag] = &sync.Po
string) *sync.Pool { decoderPoolMu.RLock() pool := decoderPoolMap[tag] if pool == nil { decoderPoolMu.RUnlock() panic(fmt.Sprintf("decoder pool not initialized for tag %q", tag)) } decoderPoolMu.RUnlock() return pool
{ "filepath": "binder/mapping.go", "language": "go", "file_size": 9610, "cut_index": 921, "middle_length": 229 }
"testing" "github.com/stretchr/testify/require" "github.com/valyala/fasthttp" ) func Test_RespHeaderBinder_Bind(t *testing.T) { t.Parallel() b := &RespHeaderBinding{ EnableSplitting: true, } require.Equal(t, "respHeader", b.Name()) type User struct { Name string `respHeader:"name"` Posts []string `...
[]string{"post1", "post2", "post3"}, user.Posts) b.Reset() require.False(t, b.EnableSplitting) } func Benchmark_RespHeaderBinder_Bind(b *testing.B) { b.ReportAllocs() binder := &RespHeaderBinding{ EnableSplitting: true, } type User struct { N
posts", "post1,post2,post3") t.Cleanup(func() { fasthttp.ReleaseResponse(resp) }) err := b.Bind(resp, &user) require.NoError(t, err) require.Equal(t, "john", user.Name) require.Equal(t, 42, user.Age) require.Equal(t,
{ "filepath": "binder/resp_header_test.go", "language": "go", "file_size": 1917, "cut_index": 537, "middle_length": 229 }
"github.com/stretchr/testify/require" ) func Test_XMLBinding_Bind(t *testing.T) { t.Parallel() b := &XMLBinding{ XMLDecoder: xml.Unmarshal, } require.Equal(t, "xml", b.Name()) type Posts struct { XMLName xml.Name `xml:"post"` Title string `xml:"title"` } type User struct { Name string `xml:...
me) require.Equal(t, 42, user.Age) require.Empty(t, user.Ignore) require.Len(t, user.Posts, 2) require.Equal(t, "post1", user.Posts[0].Title) require.Equal(t, "post2", user.Posts[1].Title) b.Reset() require.Nil(t, b.XMLDecoder) } func Test_XMLBin
> <ignore>ignore</ignore> <posts> <post> <title>post1</title> </post> <post> <title>post2</title> </post> </posts> </user> `), user) require.NoError(t, err) require.Equal(t, "john", user.Na
{ "filepath": "binder/xml_test.go", "language": "go", "file_size": 2392, "cut_index": 563, "middle_length": 229 }
"testing" "time" "github.com/stretchr/testify/require" ) func TestConfigDefault_NoConfig(t *testing.T) { t.Parallel() cfg := configDefault() require.Equal(t, DefaultConfig, cfg) } func TestConfigDefault_Custom(t *testing.T) { t.Parallel() custom := Config{ InitialInterval: 2 * time.Second, MaxBackoffTime:...
cfg := configDefault(Config{InitialInterval: 5 * time.Second}) require.Equal(t, 5*time.Second, cfg.currentInterval) require.Equal(t, 5*time.Second, cfg.InitialInterval) } func TestConfigDefault_CustomCurrentInterval(t *testing.T) { t.Parallel() cf
PartialAndNegative(t *testing.T) { t.Parallel() cfg := configDefault(Config{Multiplier: -1, MaxRetryCount: 0}) require.Equal(t, DefaultConfig, cfg) } func TestConfigDefault_CustomInitialInterval(t *testing.T) { t.Parallel()
{ "filepath": "addon/retry/config_test.go", "language": "go", "file_size": 1771, "cut_index": 537, "middle_length": 229 }
"time" ) // ExponentialBackoff is a retry mechanism for retrying some calls. type ExponentialBackoff struct { // InitialInterval is the initial time interval for backoff algorithm. InitialInterval time.Duration // MaxBackoffTime is the maximum time duration for backoff algorithm. It limits // the maximum sleep t...
{ cfg := configDefault(config...) return &ExponentialBackoff{ InitialInterval: cfg.InitialInterval, MaxBackoffTime: cfg.MaxBackoffTime, Multiplier: cfg.Multiplier, MaxRetryCount: cfg.MaxRetryCount, currentInterval: cfg.currentInterval,
int // currentInterval tracks the current sleep time. currentInterval time.Duration } // NewExponentialBackoff creates a ExponentialBackoff with default values. func NewExponentialBackoff(config ...Config) *ExponentialBackoff
{ "filepath": "addon/retry/exponential_backoff.go", "language": "go", "file_size": 2136, "cut_index": 563, "middle_length": 229 }
be nil", func() { NewWithClient(nil) }) }) } func Test_New_With_HostClient(t *testing.T) { t.Parallel() t.Run("with valid host client", func(t *testing.T) { t.Parallel() hc := &fasthttp.HostClient{Addr: "example.com:80"} client := NewWithHostClient(hc) require.NotNil(t, client) require.Equal(t, hc...
]fasthttp.BalancingClient{ &fasthttp.HostClient{Addr: "example.com:80"}, }, } client := NewWithLBClient(lb) require.NotNil(t, client) require.Equal(t, lb, client.LBClient()) require.Nil(t, client.FasthttpClient()) require.Nil(t, client
not be nil", func() { NewWithHostClient(nil) }) }) } func Test_New_With_LBClient(t *testing.T) { t.Parallel() t.Run("with valid lb client", func(t *testing.T) { t.Parallel() lb := &fasthttp.LBClient{ Clients: [
{ "filepath": "client/client_test.go", "language": "go", "file_size": 55022, "cut_index": 2151, "middle_length": 229 }
http.com/hola") url2 := []byte("http://fasthttp.com/make/fasthttp") url3 := []byte("http://fasthttp.com/make/fasthttp/great") cj := &CookieJar{} c1 := &fasthttp.Cookie{} c1.SetKey("k") c1.SetValue("v") c1.SetPath("/make/") c2 := &fasthttp.Cookie{} c2.SetKey("kk") c2.SetValue("vv") c2.SetPath("/make/fasthtt...
tp.AcquireURI() require.NoError(t, uri3.Parse(nil, url3)) cj.Set(uri1, c1, c2, c3) cookies := cj.Get(uri1) require.Len(t, cookies, 1) for _, cookie := range cookies { require.True(t, bytes.HasPrefix(uri1.Path(), cookie.Path())) } cookies = cj.G
ttp.AcquireURI() require.NoError(t, uri1.Parse(nil, url1)) uri11 := fasthttp.AcquireURI() require.NoError(t, uri11.Parse(nil, url11)) uri2 := fasthttp.AcquireURI() require.NoError(t, uri2.Parse(nil, url2)) uri3 := fastht
{ "filepath": "client/cookiejar_test.go", "language": "go", "file_size": 18430, "cut_index": 1331, "middle_length": 229 }