-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
📒 docs: Full audit of documentation #3717
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
📒 docs: Full audit of documentation #3717
Conversation
WalkthroughWidespread editorial updates across documentation files under docs/, with three documented API-like additions reflected in docs: BasicAuth Config fields, cache.New signature, encryptcookie.Config.Decryptor, and a Service.String() method documented. No runtime code changes in this diff. Changes
Sequence Diagram(s)(omitted — changes are documentation/editorial and do not alter runtime control flow) Estimated code review effort🎯 3 (Moderate) | ⏱️ ~30 minutes Possibly related PRs
Poem
✨ Finishing Touches🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 14
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (32)
docs/guide/faster-fiber.md (2)
11-15: Clarify which options are drop-in vs. custom integration.segmentio/encoding and minio/simdjson-go aren’t drop-in replacements for
encoding/json’sMarshal/Unmarshal. This list + example could mislead users.Append a short note:
- [segmentio/encoding](https://github.com/segmentio/encoding) - [minio/simdjson-go](https://github.com/minio/simdjson-go) + +Note: `goccy/go-json` and `bytedance/sonic` are drop-in replacements for `encoding/json` (Marshal/Unmarshal compatible). +`segmentio/encoding` and `minio/simdjson-go` require custom encoder/decoder functions and are not drop-in.
34-37: Verify cross-link anchors.
docs/client/rest.mdalready defines### SetJSONMarshaland### SetJSONUnmarshal(anchors #setjsonmarshal, #setjsonunmarshal).docs/api/fiber.mdlacks### JSON Encoderand### JSON Decodersections—add these headings (anchors #jsonencoder, #jsondecoder) to match the links in docs/guide/faster-fiber.md.docs/api/app.md (2)
239-246: Stack example misses fmt import; code won’t compile as shown.
fmt.Printlnis used below butfmtisn’t imported.Apply:
import ( + "fmt" "encoding/json" "log" "github.com/gofiber/fiber/v3" )
706-709: Fixtime.Second()(not a function) in Default TestConfig snippet.
time.Secondis atime.Durationconstant.Apply:
-config := fiber.TestConfig{ - Timeout: time.Second(), - FailOnTimeout: true, -} +config := fiber.TestConfig{ + Timeout: time.Second, + FailOnTimeout: true, +}docs/client/request.md (1)
5-5: Fix branding: “Gofiber” → “Fiber”.
Align with the rest of the docset.-description: >- - Request methods of Gofiber HTTP client. +description: >- + Request methods of Fiber HTTP client.docs/middleware/session.md (5)
62-71: Fix __Host- cookie requirements (missing CookiePath).__Host- cookies must have Secure=true, Path="/", and no Domain attribute. Add CookiePath to this snippet to comply.
Apply:
app.Use(session.New(session.Config{ Storage: storage, CookieSecure: true, // HTTPS only CookieHTTPOnly: true, // Prevent XSS CookieSameSite: "Lax", // CSRF protection + CookiePath: "/", // Required for __Host- cookies IdleTimeout: 30 * time.Minute, // Session timeout AbsoluteTimeout: 24 * time.Hour, // Maximum session life Extractor: session.FromCookie("__Host-session_id"), }))
471-479: Do not set CookieDomain with __Host- cookies.This block uses Extractor "__Host-session_id" but sets CookieDomain. Browsers reject __Host- cookies if Domain is present.
Apply:
- CookiePath: "/", - CookieDomain: "example.com", + CookiePath: "/", // __Host- requires Path="/" + // CookieDomain: "", // Do NOT set when using __Host-* CookieSessionOnly: false, // Persist across browser restartsOptionally drop the "__Host-" prefix if you need Domain.
539-541: Config uses Store but table documents only Storage.You use
Store: storehere, but the Config table lacks aStorerow. Add it to avoid confusion.Apply (see table below for exact diff).
698-712: Add missing Config.Store to table (precedes Storage when set).Document
StorealongsideStorageand clarify precedence.Apply:
| Property | Type | Description | Default | |---------------------|-----------------------------|-----------------------------|---------------------------| +| `Store` | `*session.Store` | Pre-built store instance. Overrides `Storage` when set. | `nil` | | `Storage` | `fiber.Storage` | Session storage backend | `memory.New()` |
386-388: Don’t echo Authorization back in responses.Setting
SourceHeaderwithKey: "Authorization"will emit Authorization in responses—unsafe. Make this extractor read-only.Apply:
- Source: session.SourceHeader, // This will set response headers - Key: "Authorization", + Source: session.SourceOther, // Read-only, do not set response values + Key: "Authorization",Alternatively, if you must return a header, use a non-sensitive one like
X-Session-ID.docs/addon/retry.md (1)
116-124: Remove unexported field from Default Config Example.
currentIntervalisn’t in the publicConfigtype. Showing it will not compile for users.Apply:
var DefaultConfig = Config{ InitialInterval: 1 * time.Second, MaxBackoffTime: 32 * time.Second, Multiplier: 2.0, MaxRetryCount: 10, - currentInterval: 1 * time.Second, }docs/middleware/expvar.md (1)
17-24: Fix example: missing imports for stdlib expvar and fmtThe snippet uses
expvar.NewIntandfmt.Sprintfbut doesn’t importexpvarandfmt, causing compile errors.import ( - "github.com/gofiber/fiber/v3" - expvarmw "github.com/gofiber/fiber/v3/middleware/expvar" + "expvar" + "fmt" + "github.com/gofiber/fiber/v3" + expvarmw "github.com/gofiber/fiber/v3/middleware/expvar" )Also applies to: 29-37
docs/client/hooks.md (1)
157-165: Fix header iteration: fasthttp headers don’t supportAll()
resp.RawResponse.Header.All()is not a fasthttp API. UseVisitAll(or a helper onResponse) to iterate safely.- fmt.Println("Response Headers:") - for key, value := range resp.RawResponse.Header.All() { - fmt.Printf("%s: %s\n", key, value) - } + fmt.Println("Response Headers:") + resp.RawResponse.Header.VisitAll(func(k, v []byte) { + fmt.Printf("%s: %s\n", string(k), string(v)) + })If the client exposes a higher-level
Headers()map, prefer that for readability.docs/api/hooks.md (1)
139-146: Broken example: duplicatelogimports and unusedos.Two packages share the same import name
log, which won’t compile;osis unused. Keep the stdliblogand drop the Fiber logger in this snippet.import ( - "log" - "os" - - "github.com/gofiber/fiber/v3" - "github.com/gofiber/fiber/v3/log" + "log" + "github.com/gofiber/fiber/v3" )Also applies to: 160-160
docs/middleware/envvar.md (1)
26-38: Add a security warning about exposing secrets.
This middleware can leak secrets (tokens, DB creds) if mounted in production. Add a caution admonition.Once your Fiber app is initialized, configure the middleware as shown: ```go // Initialize default config (exports no variables) app.Use("/expose/envvars", envvar.New()) // Or extend your config for customization app.Use("/expose/envvars", envvar.New( envvar.Config{ ExportVars: map[string]string{"testKey": "", "testDefaultKey": "testDefaultVal"}, }), )
+:::caution
+Do not expose environment variables in production. Restrict access, and only export non-sensitive keys.
+:::</blockquote></details> <details> <summary>docs/middleware/logger.md (1)</summary><blockquote> `164-178`: **Config table vs. Default Config mismatch.** Default snippet includes BeforeHandlerFunc, but the table doesn’t. Add it (and brief description), or remove from the snippet to stay consistent. ```diff | Stream | `io.Writer` | Stream is a writer where logs are written. | `os.Stdout` | +| BeforeHandlerFunc | `func(c fiber.Ctx, cfg Config)` | (If exposed) Callback invoked before logging; allows pre-processing. | `internal default` | | LoggerFunc | `func(c fiber.Ctx, data *Data, cfg Config) error` | Custom logger function for integration with logging libraries (Zerolog, Zap, Logrus, etc). Defaults to Fiber's default logger if not defined. | `see default_logger.go defaultLoggerInstance` |docs/api/redirect.md (1)
181-183: Signature bug: Message must return string.
Example uses the return as a string; returning *Redirect is inconsistent.-func (r *Redirect) Message(key string) *Redirect +func (r *Redirect) Message(key string) stringdocs/api/ctx.md (1)
2249-2251: Fix signature receiver type.-```go title="Signature" -func (c Ctx) SendStreamWriter(streamWriter func(*bufio.Writer)) error +```go title="Signature" +func (c fiber.Ctx) SendStreamWriter(streamWriter func(*bufio.Writer)) errordocs/api/bind.md (1)
608-617: Fix invalid function signature block.Current “Signature” shows struct fields inline; present the function signature only.
-```go title="Signature" -func SetParserDecoder(parserConfig fiber.ParserConfig{ - IgnoreUnknownKeys bool, - ParserType []fiber.ParserType{ - Customtype any, - Converter func(string) reflect.Value, - }, - ZeroEmpty bool, - SetAliasTag string, -}) -``` +```go title="Signature" +func SetParserDecoder(config fiber.ParserConfig) +```docs/middleware/basicauth.md (1)
29-59: Fix mismatched comment (“doe” vs “john”).The inline comment refers to “doe” but the map key is “john” in both examples.
- // "doe" hashed using SHA-256 + // "john" hashed using SHA-256 "john": "{SHA256}eZ75KhGvkY4/t0HfQpNPO1aO0tk6wd908bjUGieTKm8=", ... - // "doe" hashed using SHA-256 + // "john" hashed using SHA-256 "john": "{SHA256}eZ75KhGvkY4/t0HfQpNPO1aO0tk6wd908bjUGieTKm8=",docs/middleware/csrf.md (1)
233-247: Fix ambiguous “panic” sentence (could be misread as the inverse condition).The sentence implies a panic when names are “different”. It should panic when the extractor reads from the same-named CSRF cookie.
Apply this diff:
-If you do this, set the extractor’s `Source` to `SourceCookie` and allow the middleware to check that the cookie name is different from your CSRF cookie. It will panic if this is the case. +If you do this, set the extractor’s `Source` to `SourceCookie`. The middleware checks that the cookie name differs from your CSRF cookie and will panic if the names match.docs/api/log.md (1)
156-163: Avoid using unexported types in examples.The snippet constructs a value of defaultLogger, which appears unexported. Prefer demonstrating the public API:
-// Writing Logs to Stderr -var logger fiberlog.AllLogger[*log.Logger] = &defaultLogger{ - stdlog: log.New(os.Stderr, "", log.LstdFlags|log.Lshortfile|log.Lmicroseconds), - depth: 4, -} +// Writing Logs to Stderr +log.SetOutput(os.Stderr)docs/middleware/limiter.md (2)
88-94: Fix variable name in example (ctx → c).This won’t compile as written.
- return getUserLimit(ctx.Param("id")) + return getUserLimit(c.Param("id"))
119-136: Default Config: make MaxFunc mirror cfg.Max to avoid drift.Returning a literal duplicates Max and risks inconsistencies.
var ConfigDefault = Config{ Max: 5, - MaxFunc: func(c fiber.Ctx) int { - return 5 - }, + MaxFunc: func(c fiber.Ctx) int { return cfg.Max }, Expiration: 1 * time.Minute, KeyGenerator: func(c fiber.Ctx) string { return c.IP() }, LimitReached: func(c fiber.Ctx) error { return c.SendStatus(fiber.StatusTooManyRequests) },docs/guide/templates.md (1)
127-133: Fix missing parenthesis in AddFunc example.The example won’t compile.
engine := html.New("./views", ".html") engine.AddFunc("ToUpper", func(s string) string { return strings.ToUpper(s) -} +})docs/extra/faq.md (1)
166-168: Use RequestCtx() in v3 when calling a sub-app handler.The v3 context exposes RequestCtx(); c.Context() is outdated here.
- host.Fiber.Handler()(c.Context()) + host.Fiber.Handler()(c.RequestCtx())docs/middleware/cors.md (1)
363-367: Update Cloudflare CORS link to official CORS docs
Replace the currentdevelopers.cloudflare.com/fundamentals/get-started/reference/http-request-headers/#cf-connecting-ipURL withhttps://developers.cloudflare.com/cache/cache-security/cors/(or for R2 buckets,https://developers.cloudflare.com/r2/buckets/cors/).docs/api/state.md (3)
183-184: Fix GetBool signature type.Return type name is missing.
-func (s *State) GetBool(key string) (value, bool) +func (s *State) GetBool(key string) (bool, bool)
477-478: Fix GetService signature (remove stray brace).-func GetService[T Service](s *State, key string) (T, bool) { +func GetService[T Service](s *State, key string) (T, bool)
483-486: Correct example: function name, braces, and a realistic type.-if srv, ok := fiber.GetService[*redisService](app.State(), "someService") - fmt.Printf("Some Service: %s\n", srv.String()) -} +if srv, ok := fiber.GetService[*redis.Client](app.State(), "redis"); ok { + fmt.Printf("Redis: %s\n", srv.String()) +}docs/api/services.md (2)
319-323: Shadowing encoding/json with variable named jsonjson := json.Marshal shadows the import and confuses readers.
- json, err := json.Marshal(user) + data, err := json.Marshal(user) @@ - err = store.Set(user.Email, json, time.Hour*24) + err = store.Set(user.Email, data, time.Hour*24)
333-345: GET route key mismatch and response typeYou store by Email but fetch by :id; also returning string(user) yields a JSON-encoded string, not an object.
- app.Get("/user/:id", func(c fiber.Ctx) error { - id := c.Params("id") - user, err := store.Get(id) + app.Get("/user/:email", func(c fiber.Ctx) error { + email := c.Params("email") + b, err := store.Get(email) if err == redis.Nil { return c.Status(fiber.StatusNotFound).SendString("User not found") } else if err != nil { return c.Status(fiber.StatusInternalServerError).SendString(err.Error()) } - - return c.JSON(string(user)) + var u User + if err := json.Unmarshal(b, &u); err != nil { + return c.Status(fiber.StatusInternalServerError).SendString(err.Error()) + } + return c.JSON(u) })
🧹 Nitpick comments (89)
docs/api/app.md (1)
714-716: Tighten wording in caution block.Minor grammar polish; keeps the distinction clear.
Apply:
-This is **not** the same as supplying an empty `TestConfig{}` to -`app.Test(), but rather be the equivalent of supplying: +This is **not** the same as supplying an empty `TestConfig{}` to +`app.Test()`, but is equivalent to supplying:docs/intro.md (1)
55-55: Link to utils or qualify package to reduce ambiguity.Readers may not know where
utils.CopyString/CopyBytescome from. Add a link or qualify once.Apply (either approach):
-If it's disabled, use `utils.CopyString` and `utils.CopyBytes` to allocate only when necessary. +If it's disabled, use `utils.CopyString` and `utils.CopyBytes` (package `github.com/gofiber/fiber/v3/utils`) to allocate only when necessary.docs/middleware/rewrite.md (3)
17-21: Tighten “Next” description per style; keep subject explicit.Minor grammar tweak; aligns with similar middleware docs.
Apply:
-| Next | `func(fiber.Ctx) bool` | Skip when function returns `true`. | `nil` | +| Next | `func(fiber.Ctx) bool` | Skip the middleware when the function returns `true`. | `nil` |
22-24: Nice addition about map order.Precedence caveat is helpful. Consider adding one line on deterministic alternatives (e.g., slice of rules) if needed later.
39-45: Example spacing/style improved; also recommend showing precedence-sensitive rules.Optional: add a short example demonstrating how overlapping rules can surprise due to map order.
docs/api/constants.md (1)
168-168: Optional: align headers section title with new style.For consistency, consider changing “HTTP Headers were copied from net/http.” to a heading like “### HTTP headers (mirrors
net/http)”.-HTTP Headers were copied from net/http. +### HTTP headers (mirrors `net/http`)docs/middleware/requestid.md (2)
27-40: Avoid using a predictable generator in examples.
Using a fixed "static-id" can be miscopied into production. Suggest demonstrating UUIDv4.Apply:
app.Use(requestid.New(requestid.Config{ - Header: "X-Custom-Header", - Generator: func() string { - return "static-id" - }, + Header: "X-Custom-Header", + Generator: utils.UUIDv4, }))
56-61: Tighten table wording and defaults.
Consider linking/defaulting Header to the constant to reduce duplication.-| Header | `string` | Header key used to store the request ID. | "X-Request-ID" | +| Header | `string` | Header key used to store the request ID. | `fiber.HeaderXRequestID` |docs/client/examples.md (2)
14-16: Add HTTPS caution for Basic Auth.
Basic credentials are only base64-encoded; advise using HTTPS even in examples to avoid sending secrets in cleartext.-Clients send credentials via the `Authorization` header, while the server -stores hashed passwords as shown in the middleware example. +Clients send credentials via the `Authorization` header (use HTTPS), while the server +stores hashed passwords as shown in the middleware example.
33-38: Prefer HTTPS in the client example.
If feasible, use https://localhost:3000 (aligned with TLS example) or add a note that plain HTTP is for local demo only.-resp, err := cc.Get("http://localhost:3000", client.Config{ +resp, err := cc.Get("http://localhost:3000", client.Config{ // use HTTPS in productiondocs/guide/utils.md (1)
56-63: Clarify single-function overload behavior.
Go doesn’t support overloading; this is one function with an optional value. Add a one-liner to preempt confusion.-// Set a value +// One function with an optional value parameter: +// Set a value ... -// Get a value +// Get a valuedocs/middleware/skip.md (1)
17-24: Import block is helpful; add missing log for example.
Example below uses log.Fatal; include it here for copy/paste builds.import ( "github.com/gofiber/fiber/v3" "github.com/gofiber/fiber/v3/middleware/skip" + "log" )docs/middleware/keyauth.md (1)
49-53: Add caution: avoid storing API keys in cookies.Cookies are client-controlled and often logged. Prefer headers for API keys; use cookies for session tokens instead.
Apply:
// Register middleware before the routes that need it app.Use(keyauth.New(keyauth.Config{ Extractor: keyauth.FromCookie("access_token"), Validator: validateAPIKey, })) + + // :::caution + // Storing static API keys in cookies is discouraged. Prefer headers for API keys, + // and use cookies for session tokens issued after authentication. + // :::docs/guide/grouping.md (1)
33-51: Show the “optional handler” in this snippet.Text says groups can include an optional handler, but this example doesn’t demonstrate it. Add a simple middleware function to the Group call.
I can propose a concrete snippet mirroring the “Group Handlers” style if you’d like.
docs/addon/retry.md (1)
39-50: Reuse client across retries.Creating a client per attempt adds overhead. Instantiate once outside the closure.
Apply:
func main() { - expBackoff := retry.NewExponentialBackoff(retry.Config{}) + expBackoff := retry.NewExponentialBackoff(retry.Config{}) + httpClient := client.New() @@ - err = expBackoff.Retry(func() error { - client := client.New() - resp, err = client.Get("https://gofiber.io") + err = expBackoff.Retry(func() error { + resp, err = httpClient.Get("https://gofiber.io")Also applies to: 48-55
docs/client/response.md (1)
5-5: Use “Fiber” branding consistently.Frontmatter still says “Gofiber”.
Apply:
- Response methods of Gofiber HTTP client. + Response methods of Fiber HTTP client.docs/middleware/adaptor.md (2)
7-7: Tighten opening for accuracy and scopeConsider explicitly mentioning “adaptor between Fiber v3 and net/http” and that conversions preserve request/response bodies and context where possible; link to limitations below (e.g., streaming, hijacking). This helps set expectations.
49-51: Examples: add brief caveats on behavior
- Mention that net/http middleware adapted via
HTTPMiddlewareruns before downstream Fiber handlers in the same route chain.- For
FiberApp, note that it returns anhttp.Handler(Func)suitable forhttp.ListenAndServe, and that not all net/http-only features (e.g., connection hijacking) are supported.Also applies to: 77-83, 109-116, 142-144
docs/middleware/expvar.md (1)
39-59: Clarify filter param and show minimal sampleAdd that
ris a regexp applied to keys, consistent with stdlib expvar, and include a quick note that filtering reduces payload for largememstats.-Visit `/debug/vars` to see all variables, and append `?r=key` to filter the output. +Visit `/debug/vars` to see all variables. Append `?r=<regexp>` (e.g., `?r=^c`) to regexp-filter keys server-side to cut payload size.docs/middleware/etag.md (3)
7-7: Tighten intro and add caveat about conditional requestsConsider stating that ETag enables 304 Not Modified responses when validators match, reducing bandwidth and latency.
-ETag middleware for [Fiber](https://github.com/gofiber/fiber) that helps caches validate responses and saves bandwidth by avoiding full retransmits when content is unchanged. +ETag middleware for [Fiber](https://github.com/gofiber/fiber) that validates cached responses and enables 304 Not Modified when content is unchanged.
26-46: Example clarity: separate “default” vs “customized” flowsTwo handlers for
/in one snippet can confuse readers copying the code. Present them as alternatives or split into two snippets.-// Initialize default config -app.Use(etag.New()) -// GET / -> ETag: "13-1831710635" +// Option A: default config +app.Use(etag.New()) +// GET / -> ETag: "13-1831710635" @@ -// Or extend your config for customization -app.Use(etag.New(etag.Config{ +// Option B: customized config +app.Use(etag.New(etag.Config{
58-60: Config wording: clarify HSTS-related caveats and directive semantics
- Note that HSTS headers are only sent over HTTPS.
- For
HSTSExcludeSubdomains, clarify it omits theincludeSubDomainsdirective when true.-| HSTSExcludeSubdomains | `bool` | Disables HSTS on subdomains when `true`. | false | +| HSTSExcludeSubdomains | `bool` | Omits the `includeSubDomains` directive when `true`. | false |Add a short tip below the table: “HSTS is only effective over HTTPS; browsers ignore it on HTTP.”
docs/client/hooks.md (2)
93-98: Avoid documenting unexported/internal hook namesIf
parserRequestURL,parserRequestHeader,parserRequestBody, andloggerare internal implementation details, call them “built-in request/response hooks (URL parsing, header setup, body serialization, cookie parsing, logging)” without naming unexported symbols to prevent API drift.-- **parserRequestURL**: Normalizes and customizes the URL based on path and query parameters. Required for `PathParam` and `QueryParam` methods. -- **parserRequestHeader**: Sets request headers, cookies, content type, referer, and user agent based on client and request properties. -- **parserRequestBody**: Automatically serializes the request body (JSON, XML, form, file uploads, etc.). +- URL parser: normalizes and assembles the URL from base, path, and query (required for `PathParam`/`QueryParam`). +- Header builder: sets headers, cookies, content type, referer, and user agent from client/request. +- Body serializer: encodes JSON, XML, form fields, and files as needed. @@ -- **logger**: Logs information about the raw request and response. It uses the `log.CommonLogger` interface. +- Logger: logs raw request/response metadata (uses `log.CommonLogger`).Also applies to: 201-205
256-257: Order and failure semantics: add explicit stop-on-error note for both hook kindsYou noted error short-circuiting above; reference it here too so readers don’t miss it when skimming execution order.
-Hooks run in FIFO order (first in, first out), so they're executed in the order you add them. Keep this in mind when adding multiple hooks, as the order can affect the outcome. +Hooks run in FIFO order (first in, first out) and stop at the first hook that returns an error.docs/middleware/helmet.md (3)
7-7: Small clarity tweak“Common security headers” → “common HTTP security headers” for precision.
-Helmet secures your app by adding common security headers. +Helmet secures your app by adding common HTTP security headers.
17-19: Consistency: add a one-line import snippet (mirrors other middleware docs)Other middleware pages in this PR include an import block; add one here for parity.
Once your Fiber app is initialized, add the middleware: ```go +import ( + "github.com/gofiber/fiber/v3" + "github.com/gofiber/fiber/v3/middleware/helmet" +) + package main
50-68: Config descriptions: tighten wording for HSTS and deprecation note for X-XSS-Protection
- Clarify
HSTSExcludeSubdomainssemantics (omitincludeSubDomains).- Consider a short note that
X-XSS-Protectionis deprecated in modern browsers and generally unnecessary.-| HSTSExcludeSubdomains | `bool` | Disables HSTS on subdomains when `true`. | false | +| HSTSExcludeSubdomains | `bool` | Omits the `includeSubDomains` directive when `true`. | false |Add a footnote: “X-XSS-Protection is obsolete in modern browsers; leave at default unless you target legacy clients.”
docs/middleware/timeout.md (3)
7-9: Tweak phrasing for clarity and flow.Replace “and returns
408 Request Timeoutwhen the deadline is exceeded.” with “and returns a408 Request Timeoutif the deadline is exceeded.” Also drop the comma before “and” to avoid a splice.-The timeout middleware aborts handlers that run too long. It wraps them with -`context.WithTimeout`, exposes the derived context through `c.Context()`, and -returns `408 Request Timeout` when the deadline is exceeded. +The timeout middleware aborts handlers that run too long. It wraps them with +`context.WithTimeout` and exposes the derived context through `c.Context()`. It +returns a `408 Request Timeout` if the deadline is exceeded.
12-15: Strengthen the per-route guidance with a do/don’t snippet.A short code contrast helps prevent misuse with
app.Use/c.Next().:::caution `timeout.New` wraps your final handler and can't be added with `app.Use` or used in a middleware chain. Register it per route and avoid calling `c.Next()` inside the wrapped handler—doing so will panic. ::: + +```go +// Don't: +app.Use(timeout.New(handler, timeout.Config{Timeout: 2 * time.Second})) // ❌ will panic if handler calls c.Next() + +// Do: +app.Get("/sleep/:delay", timeout.New(handler, timeout.Config{Timeout: 2 * time.Second})) // ✅ per-route +```
128-144: Minor Go idioms in DB example.Use
txand handle errors explicitly to improve readability.- handler := func(ctx fiber.Ctx) error { - tran := db.WithContext(ctx.Context()).Begin() - - if tran = tran.Exec("SELECT pg_sleep(50)"); tran.Error != nil { - return tran.Error - } - - if tran = tran.Commit(); tran.Error != nil { - return tran.Error - } + handler := func(c fiber.Ctx) error { + tx := db.WithContext(c.Context()).Begin() + if err := tx.Exec("SELECT pg_sleep(50)").Error; err != nil { + return err + } + if err := tx.Commit().Error; err != nil { + return err + } return nil }docs/middleware/pprof.md (2)
26-38: Good usage flow; add an access-control note.Profiling endpoints often expose sensitive data. Suggest a short note to gate with
Nextor only enable in non-production.// The resulting URL is "/endpoint-prefix/debug/pprof/" + +// Tip: Expose pprof only in non-production or behind auth, e.g., using Next: +// app.Use(pprof.New(pprof.Config{ +// Next: func(c fiber.Ctx) bool { return !isAuthorized(c) }, +// }))
49-53: IncludePrefixin Default Config for completeness.Documenting the zero value helps readers.
var ConfigDefault = Config{ Next: nil, + Prefix: "", }docs/middleware/recover.md (2)
26-36: Add placement guidance.Recommend registering Recover early to catch panics in downstream handlers.
// Initialize default config app.Use(recoverer.New()) // Panics in subsequent handlers are caught by the middleware +// Tip: Register Recover as one of the first middlewares: +// app := fiber.New() +// app.Use(recoverer.New()) // before other app.Use / routes
40-45: Tighten descriptions in table.Minor editorial tweaks for consistency (imperatives).
-| EnableStackTrace | `bool` | Capture and include a stack trace in error responses. | `false` | -| StackTraceHandler | `func(fiber.Ctx, any)` | Handle the captured stack trace when enabled. | defaultStackTraceHandler | +| EnableStackTrace | `bool` | Include a stack trace in error responses. | `false` | +| StackTraceHandler | `func(fiber.Ctx, any)` | Process the captured stack trace when enabled. | defaultStackTraceHandler |docs/middleware/compress.md (2)
10-11: Future-proof the fasthttp link.Pinned line numbers can drift. Prefer linking to the symbol or adding the threshold inline.
-Bodies smaller than 200 bytes remain uncompressed because compression would likely increase their size and waste CPU cycles. [See the fasthttp source](https://github.com/valyala/fasthttp/blob/497922a21ef4b314f393887e9c6147b8c3e3eda4/http.go#L1713-L1715). +Bodies smaller than ~200 bytes remain uncompressed because compression may increase size and waste CPU. See fasthttp’s implementation (min compress size).
52-56: Table wording consistency.Use imperative voice and remove “this” for brevity.
-| Next | `func(fiber.Ctx) bool` | Skips this middleware when the function returns `true`. | `nil` | -| Level | `Level` | Compression level to use. | `LevelDefault (0)` | +| Next | `func(fiber.Ctx) bool` | Skip the middleware when the function returns `true`. | `nil` | +| Level | `Level` | Choose the compression level. | `LevelDefault (0)` |docs/middleware/envvar.md (1)
17-24: Imports in examples: align with docs style.
Fiber docs often omit imports in repeated examples. Consider keeping this, but ensure consistency across middleware docs in this PR.docs/middleware/logger.md (2)
17-24: Imports in examples: keep consistent across docs.
This PR adds explicit imports widely; ensure all middleware docs follow the same pattern.
62-71: File stream example: mention rotation.
Consider a brief note on log rotation (e.g., reopen on SIGHUP or use a rolling writer) to avoid growing files in production.docs/api/redirect.md (2)
37-47: Example contains multiple returns in one handler.
This won’t compile if pasted verbatim. Show alternatives without multiple executable returns.app.Get("/", func(c fiber.Ctx) error { - // => HTTP - GET 303 /foo/bar - return c.Redirect().To("/foo/bar") - // => HTTP - GET 303 ../login - return c.Redirect().To("../login") - // => HTTP - GET 303 http://example.com - return c.Redirect().To("http://example.com") - // => HTTP - GET 301 https://example.com - return c.Redirect().Status(301).To("http://example.com") + // Examples — pick one: + // return c.Redirect().To("/foo/bar") + // return c.Redirect().To("../login") + // return c.Redirect().To("http://example.com") + return c.Redirect().Status(301).To("http://example.com") })
92-96: Clarify “referer.”
Consider “Referer (HTTP header)” to avoid spell-check noise while staying accurate.-Redirects to the referer. If it's missing, fall back to the provided URL. You can also set the status code. +Redirects to the Referer (HTTP header). If it's missing, fall back to the provided URL. You can also set the status code.docs/middleware/favicon.md (2)
11-13: Link “Static middleware” for clarity.Add a link to the Static middleware page when suggesting multiple icons.
-This middleware only serves the default `/favicon.ico` (or a [custom URL](#config)). For multiple icons, use the Static middleware. +This middleware only serves the default `/favicon.ico` (or a [custom URL](#config)). For multiple icons, use the [Static middleware](../middleware/static.md).
49-49: Minor grammar polish.Use consistent “returns true” phrasing across docs.
-| Next | `func(fiber.Ctx) bool` | Next defines a function to skip this middleware when it returns true. | `nil` | +| Next | `func(fiber.Ctx) bool` | Next defines a function to skip this middleware when it returns true. | `nil` |docs/middleware/healthcheck.md (1)
58-63: Clarify non-GET behavior on app.Get vs app.All.Docs elsewhere note subtle differences (404 vs pass-through/405) depending on registration. Consider adding this nuance.
-The middleware responds only to GET. Use `app.All` to expose a probe on every method; other methods fall through to the next handler: +The middleware responds only to GET. With `app.Get`, other methods return 405/404 based on routing. To expose a probe on every method, use `app.All`; non‑GET methods fall through to the next handler (or 404 if none matches):docs/api/ctx.md (3)
2054-2058: Fix duplicated/mangled caution text for Early Hints.-:::caution -This feature requires HTTP/2 or newer. Some legacy HTTP/1.1 clients may not -Early Hints (`103` responses) are supported in HTTP/2 and newer. Older HTTP/1.1 clients may ignore these interim responses or misbehave when receiving them. -::: +:::caution +Requires HTTP/2 or newer. Some HTTP/1.1 clients may ignore or mishandle 103 Early Hints. +:::
2077-2121: Remove duplicate title attribute and fix signature formatting.-```go title="Config" title="Config" +```go title="Config" @@ -```go title="Signature" title="Signature" +```go title="Signature"
2191-2194: Avoid linking to a specific commit for status codes.Replace hard-coded source link with a stable docs page (e.g., Constants) to prevent rot.
-You can find all used status codes and messages [in the Fiber source code](https://github.com/gofiber/fiber/blob/dffab20bcdf4f3597d2c74633a7705a517d2c8c2/utils.go#L183-L244). +See the list of HTTP status codes in [Constants](./constants.md).docs/api/bind.md (1)
675-682: Prefix curl examples with a fenced code block language.Minor formatting nit: ensure these lines remain inside the fenced bash block (they are now, just keep consistent across sections).
docs/guide/validation.md (1)
36-39: List all common bind targets for clarity.Include Params and Header to reflect the full surface.
- // Works with all bind methods—Body, Query, Form, etc. - if err := c.Bind().Body(user); err != nil { // validation errors are returned here + // Works with all bind methods—Body, Query, Form, Params, Header, etc. + if err := c.Bind().Body(user); err != nil { // validation errors are returned heredocs/middleware/cache.md (5)
7-7: Scope “stored headers” to config to avoid overstatement.Content-Type and other headers are only persisted when StoreResponseHeaders is enabled.
-Cache middleware ... stores the body, `Content-Type`, and status code ... +Cache middleware ... stores the status and body, and can optionally store headers (e.g., `Content-Type`) depending on `StoreResponseHeaders` ...
34-35: Add RFC 9111 (HTTP Caching).Supplement RFC 7231 with RFC 9111, the current caching spec.
-For more about cacheable status codes and RFC 7231, see: +For more about cacheable status codes and semantics, see: +- RFC 9111 — HTTP Caching
48-56: Imports missing for used packages.Examples below use time and strconv; add them to the import block.
import ( "github.com/gofiber/fiber/v3" "github.com/gofiber/fiber/v3/middleware/cache" "github.com/gofiber/utils/v2" + "strconv" + "time" )
103-104: Clarify effect: “bypass read and write.”Explicitly state that returning true skips both lookup and store.
-`CacheInvalidator` defines custom invalidation rules. Return `true` to bypass the cache. +`CacheInvalidator` defines custom invalidation rules. Return `true` to bypass cache lookup and storage for the request.
107-120: Two small table tweaks.
- CacheHeader values: code uses lowercase tokens; keep as-is but consider backticks around values.
- ExpirationGenerator wording: it generates durations, not “keys.”
-| ExpirationGenerator | `func(fiber.Ctx, *cache.Config) time.Duration` | ExpirationGenerator allows you to generate custom expiration keys based on the request. | `nil` | +| ExpirationGenerator | `func(fiber.Ctx, *cache.Config) time.Duration` | Generate a custom expiration duration based on the request/response. | `nil` |docs/middleware/earlydata.md (2)
9-9: Show how to enable TrustProxy.Add a one-line snippet to reduce misconfiguration.
-Enable Fiber's `TrustProxy` option before using this middleware to avoid spoofed client headers. +Enable Fiber's `TrustProxy` option before using this middleware to avoid spoofed client headers: + +```go +app := fiber.New(fiber.Config{ TrustProxy: true }) +```
53-59: Tighten config phrasing.Minor grammar polish.
-| Next | `func(fiber.Ctx) bool` | Skip this middleware when the function returns true. | `nil` | +| Next | `func(fiber.Ctx) bool` | Skip this middleware when the function returns `true`. | `nil` | -| IsEarlyData | `func(fiber.Ctx) bool` | Reports whether the request used early data. | Function checking if "Early-Data" header equals "1" | +| IsEarlyData | `func(fiber.Ctx) bool` | Report whether the request used early data. | Checks if `Early-Data` header equals `1` | -| AllowEarlyData | `func(fiber.Ctx) bool` | Decides if an early-data request should be allowed. | Function rejecting on unsafe and allowing safe methods | +| AllowEarlyData | `func(fiber.Ctx) bool` | Decide if an early-data request should be allowed. | Rejects unsafe; allows safe methods |docs/middleware/basicauth.md (2)
66-68: Hash prefix guidance LGTM, but add security note.Encourage bcrypt/argon2 over raw SHA digests for stored passwords.
- `"{SHA512}"` or `"{SHA256}"` followed by a base64-encoded digest - standard bcrypt strings beginning with `$2` +> Security: Prefer bcrypt (or argon2 via a custom Authorizer) over raw SHA digests for password storage.
98-105: Clarify Authorizer precedence and Unauthorized semantics.Note that when Authorizer is set, it overrides Users-map checks; and Unauthorized is only used on failure.
-| Authorizer | `func(string, string, fiber.Ctx) bool` | Authorizer defines a function to check the credentials. It will be called with a username, password, and the current context and is expected to return true or false to indicate approval. | `nil` | +| Authorizer | `func(string, string, fiber.Ctx) bool` | Optional custom credential check. When set, it takes precedence over `Users`. Return `true` to allow; `false` to fail. | `nil` | -| Unauthorized | `fiber.Handler` | Unauthorized defines the response body for unauthorized responses. | `nil` | +| Unauthorized | `fiber.Handler` | Custom response for unauthorized requests (used when auth fails). | `nil` |docs/guide/advance-format.md (3)
11-15: Clarify MsgPack binding vs bundling to avoid mixed signals.“Out of the box” binding plus the later note about not bundling a MsgPack implementation can read as contradictory. Suggest tightening the first bullets to state binding support and when encoders/decoders must be configured; AutoFormat types are correct. (docs.gofiber.io)
- Fiber can bind requests with the `application/vnd.msgpack` content type out of the box. See the [Binding documentation](../api/bind.md#msgpack) for details. - Use `Bind().MsgPack()` to bind data to structs, similar to JSON. `Ctx.AutoFormat()` responds with MsgPack when the `Accept` header is `application/vnd.msgpack`. See the [AutoFormat documentation](../api/ctx.md#autoformat) for more. + Fiber can bind request bodies with the `application/vnd.msgpack` content type. See the [Binding documentation](../api/bind.md#msgpack). + Use `Bind().MsgPack()` to bind data to structs (like JSON). To respond, configure a MsgPack encoder/decoder (see below) and `Ctx.AutoFormat()` will select MsgPack when the `Accept` header is `application/vnd.msgpack`. See the [AutoFormat docs](../api/ctx.md#autoformat).
31-31: Fix reference direction (“below” → “above”).The libraries are listed above, not below.
-> **Note:** Fiber doesn't bundle a MsgPack implementation because it's outside the Go standard library. Pick one of the popular libraries in the ecosystem; the two below are widely used and well maintained. +> **Note:** Fiber doesn't bundle a MsgPack implementation because it's outside the Go standard library. Pick one of the popular libraries in the ecosystem; the two above are widely used and well maintained.
3-3: Emoji/title mismatch.“Advanced Format” isn’t an error topic; consider a neutral or tools emoji.
-title: 🐛 Advanced Format +title: 🧰 Advanced Formatsdocs/client/rest.md (3)
10-10: Use canonical name “fasthttp.”Library name is “fasthttp” (lowercase) in code and docs. (docs.gofiber.io)
-The Fiber Client is a high-performance HTTP client built on FastHTTP. It handles both internal service calls and external requests with minimal overhead. +The Fiber Client is a high-performance HTTP client built on fasthttp. It handles both internal service calls and external requests with minimal overhead.
214-218: Tighten pooling language for R().Minor reword for clarity; matches Acquire/Release semantics shown elsewhere. (docs.gofiber.io)
-**R** gets a `Request` object from the pool. Call `ReleaseRequest` when finished. +**R** gets a pooled `Request`. Call `ReleaseRequest` when finished to avoid extra allocations.
48-49: Grammar nit.Hyphen after the previous sentence isn’t needed in a bullet list.
-See [examples](examples.md) for more detailed usage. +See [examples](examples.md) for more detailed usage.docs/api/fiber.md (1)
53-57: TrustProxy description: keep intent but simplify conditional sentence.The behavior matches current “Next” docs but the long sentence is hard to parse. Suggested split without changing meaning. (docs.gofiber.io)
-| <Reference id="trustproxy">TrustProxy</Reference> | `bool` | When true, Fiber validates the proxy IP against `TrustProxyConfig.Proxies`. <br /><br />By default, `c.Protocol()`, `c.IP()`, and `c.Hostname()` read values from standard X-Forwarded headers. If the remote IP matches a trusted proxy, these methods behave as if `TrustProxy` were disabled. Otherwise, `c.Protocol()` reflects the connection scheme, `c.IP()` uses `RemoteIP()` from Fasthttp, and `c.Hostname()` uses `fasthttp.Request.URI().Host()` | `false` | +| <Reference id="trustproxy">TrustProxy</Reference> | `bool` | When true, Fiber validates the remote IP against `TrustProxyConfig.Proxies`.<br /><br />By default, `c.Protocol()`, `c.IP()`, and `c.Hostname()` read X‑Forwarded headers. If the remote IP is trusted, these behave as if `TrustProxy` were disabled. If it isn’t trusted, `c.Protocol()` reflects the actual connection (HTTPS if TLS, otherwise HTTP), `c.IP()` uses `RemoteIP()` from fasthttp, and `c.Hostname()` uses `fasthttp.Request.URI().Host()`. | `false` |Also applies to: 59-61
docs/guide/error-handling.md (1)
30-53: Capitalize “Fiber” in the panic message.Minor copy edit for brand consistency.
- panic("This panic is caught by fiber") + panic("This panic is caught by Fiber")docs/api/log.md (3)
55-63: Tighten wording on message key once.Current line is fine; to reduce repetition later, consider: “Entries populate the configured message key (default: msg).”
108-110: Contrib adapters mention is helpful.Consider linking directly to fiberzap and fiberzerolog for convenience.
205-212: Typed DefaultLogger example is useful; add alt without generics.Consider adding a short variant using type assertion for users not using type parameters.
logger := fiberlog.DefaultLogger() if std, ok := logger.Logger().(*log.Logger); ok { std.SetFlags(0) }docs/middleware/limiter.md (2)
34-58: Example compiles, but consider header casing for X-Forwarded-For.Go’s fasthttp is case-insensitive, but conventional casing improves readability: "X-Forwarded-For". Optional.
98-111: Grammar/punctuation in table rows.Use consistent perioding and sentence case for descriptions (“when it returns true”, etc.). Apply across rows for Next/Max/KeyGenerator/LimitReached/Skip*.
Also applies to: 119-136
docs/guide/templates.md (1)
90-99: Tab label mismatch.Label “layouts/index.html” conflicts with earlier “views” path and may confuse readers.
-<TabItem value="index" label="layouts/index.html"> +<TabItem value="index" label="views/index.html">docs/middleware/proxy.md (1)
63-72: Handler example: route reuse may confuse.You re-use path “/proxy” for multiple examples below. Consider unique paths per example to avoid copy-paste confusion.
docs/middleware/encryptcookie.md (2)
59-61: Clarify “bytes” vs “base64” to prevent misconfigurations.State that if using base64, the decoded key must be 16/24/32 bytes.
-Use an encoded key of 16, 24, or 32 bytes to select AES‑128, AES‑192, or AES‑256‑GCM. Generate a stable key with `openssl rand -base64 32` or `encryptcookie.GenerateKey(32)` and store it securely. Generating a new key on each startup renders existing cookies unreadable. +Use a key of 16, 24, or 32 bytes to select AES‑128, AES‑192, or AES‑256‑GCM. If you use base64, it must decode to 16/24/32 bytes. Generate a stable key with `openssl rand -base64 32` (decodes to 32 bytes) or `encryptcookie.GenerateKey(32)` and store it securely. Regenerating the key on startup makes existing cookies unreadable.
65-72: Tighten Config.Key description to remove ambiguity.Explicitly mention “decoded length” when base64 is used.
-| Key | `string` | A base64-encoded unique key to encode & decode cookies. Required. Key length should be 16, 24, or 32 bytes. | (No default, required field) | +| Key | `string` | Key used to encrypt/decrypt cookie values. If base64-encoded, it must decode to 16, 24, or 32 bytes. Required. | (No default, required field) |docs/extra/faq.md (1)
99-99: Add alt text for the Discord image.Complies with MD045 and improves accessibility.
- +docs/guide/routing.md (3)
51-52: Use a local docs link for Params.External fiber.wiki link is inconsistent with the rest of the docs.
-Route parameters are dynamic segments in a path, either named or unnamed, used to capture values from the URL. Retrieve them with the [Params](https://fiber.wiki/context#params) function using the parameter name or, for unnamed parameters, the wildcard (`*`) or plus (`+`) symbol with an index. +Route parameters are dynamic segments in a path, either named or unnamed, used to capture values from the URL. Retrieve them with [Params](../api/ctx.md#params) using the parameter name or, for unnamed parameters, the wildcard (`*`) or plus (`+`) symbol with an index.
160-160: Close the parenthesis in the maxLen description.Small table typo.
-| maxLen(value) | `:filename<maxLen(8)>` | MyFile (must be no more than 8 characters | +| maxLen(value) | `:filename<maxLen(8)>` | MyFile (must be no more than 8 characters) |
209-210: Soften the “no runtime overhead” claim for regex constraints.Compilation is done at registration time; matching still adds per-request work.
-Fiber precompiles the regex when registering routes, so regex constraints add no runtime overhead. +Fiber precompiles the regex when registering routes, so there’s no per-request compile cost (only matching at request time).docs/middleware/cors.md (3)
48-55: Avoid registering CORS twice in the “Custom configuration” example.Showing default then custom in one block can lead to copy/paste duplicates.
-// Initialize default config -app.Use(cors.New()) - -// Or extend your config for customization +// Custom configuration app.Use(cors.New(cors.Config{ AllowOrigins: []string{"https://gofiber.io", "https://gofiber.net"}, AllowHeaders: []string{"Origin", "Content-Type", "Accept"}, }))
192-193: Fix punctuation (extra colon).-- **Programmatic origin validation:**: The middleware also handles the `AllowOriginsFunc` option, which allows you to programmatically determine if an origin is allowed. If `AllowOriginsFunc` returns `true` for an origin, the middleware sets the `Access-Control-Allow-Origin` header to that origin. +- **Programmatic origin validation:** The middleware also handles the `AllowOriginsFunc` option, which allows you to programmatically determine if an origin is allowed. If `AllowOriginsFunc` returns `true` for an origin, the middleware sets the `Access-Control-Allow-Origin` header to that origin.
254-255: Grammar: singular OPTIONS request.-If the `Access-Control-Request-Method` header is missing from an OPTIONS request, Fiber will not recognize them as CORS preflight requests. +If the `Access-Control-Request-Method` header is missing from an OPTIONS request, Fiber will not recognize it as a CORS preflight request.docs/api/state.md (1)
204-208: Remove “Signature” title from a usage snippet.This block shows usage, not a signature.
-```go title="Signature" +```go if ratio, ok := app.State().GetFloat64("scalingFactor"); ok { fmt.Printf("Scaling Factor: %f\n", ratio) }docs/api/services.md (6)
7-9: Clarify startup/shutdown behavior and cross-reference State docsGood summary. To align with prior decisions: Fiber starts services during app initialization (via New) and will panic on startup failure. Consider adding that nuance.
Apply:
-Services wrap external dependencies. Register them in the application's state, and Fiber starts and stops them automatically—useful during development and testing. +Services wrap external dependencies. Register them in the application's state, and Fiber starts and stops them automatically. Startup failures will abort the process to avoid running in a degraded state—useful during development and testing.
94-104: Pin container image tag for reproducibilityAvoid :latest in examples to prevent flaky docs.
- c, err := tcredis.Run(ctx, "redis:latest") + c, err := tcredis.Run(ctx, "redis:7.2-alpine")
139-151: Reuse of cancel adds cognitive loadTwo different contexts reuse the same cancel identifier. Use distinct names.
- startupCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() + startupCtx, startupCancel := context.WithTimeout(context.Background(), 10*time.Second) + defer startupCancel() @@ - shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() + shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second) + defer shutdownCancel()
308-312: Wording: “GoFiber session store” → “Fiber Redis storage”Minor terminology fix.
- // define a GoFiber session store, backed by the Redis service + // Define a Fiber Redis storage, backed by the Redis service
230-236: Avoid :latest tag here tooSame reproducibility concern as above.
- c, err := tcredis.Run(ctx, "redis:latest") + c, err := tcredis.Run(ctx, "redis:7.2-alpine")
287-291: Logger comment capitalization and clarityTiny nit for consistency.
- // Initialize default config + // Initialize default middleware
|
/gemini review |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review
This pull request provides a comprehensive audit of the Fiber documentation. The changes significantly improve the clarity, conciseness, and accuracy of the content across numerous files. The rewording of descriptions, correction of typos, and enhancement of code examples make the documentation much more professional and easier to understand for developers. Excellent work on this documentation overhaul!
|
@gaby can you check the ai hints and after the adjustments i will merge |
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull Request Overview
Full audit and rewrite of Fiber documentation to improve clarity, consistency, and conciseness across all middleware, guides, API references, and client documentation.
- Complete rewrite of all middleware documentation for better readability and standardized structure
- Updated guide sections with clearer explanations and more accessible language
- Refined API documentation to improve consistency and remove redundancy
Reviewed Changes
Copilot reviewed 56 out of 56 changed files in this pull request and generated no comments.
Show a summary per file
| File | Description |
|---|---|
| docs/middleware/*.md | Comprehensive rewrite of all 29 middleware docs for clarity and consistency |
| docs/guide/*.md | Updated all guide sections with clearer language and improved examples |
| docs/api/*.md | Refined API documentation for better readability and consistency |
| docs/client/*.md | Updated client documentation with cleaner explanations |
| docs/extra/*.md | Improved FAQ and benchmarks sections |
| docs/intro.md | Minor clarity improvements to introduction |
| docs/addon/retry.md | Enhanced retry addon documentation |
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
|
@codex review |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Codex Review: Here are some suggestions.
Reply with @codex fix comments to fix any unresolved comments.
About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you open a pull request for review, mark a draft as ready, or comment "@codex review". If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex fix this CI failure" or "@codex address that feedback".
|
@codex fix comments, the value should be base64 encoded hash |
Summary
Testing
Notes
|
Updated hashed passwords for users in the configuration.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
docs/middleware/basicauth.md (1)
43-59: Avoid suggesting an Authorizer that bypasses password checks.
This example returns true based only on username, effectively disabling authentication. Recommend demonstrating an Authorizer that validates both user and pass or explicitly warn that this bypasses password verification.- Authorizer: func(user, pass string, c fiber.Ctx) bool { - // custom validation logic - return (user == "john" || user == "admin") - }, + Authorizer: func(user, pass string, c fiber.Ctx) bool { + // Example: enforce custom rule AND verify password against a hash + // (Pseudo) Replace with your own user store / hashing: + return user == "john" && basicauth.CheckSHA256(pass, + "K7gNU3sdo+OL0wNhqoVWhr3g6s1xYv72ol/pe/Unols=") + },
♻️ Duplicate comments (1)
docs/middleware/basicauth.md (1)
69-71: Doc/code mismatch: “no prefix = SHA-256 (hex/base64)” likely not implemented.
Previous verification found no fallback handling in middleware code (no prefix parsing, hex/base64 decode). Either remove this claim or implement the behavior.If you keep docs-only changes, replace with: “Unprefixed values are treated as opaque and compared byte-for-byte; provide a prefix to use hashed verification.”
-If no prefix is present, the value is interpreted as a SHA-256 digest encoded in -hex or base64. Plaintext passwords are rejected. +If no prefix is present, behavior is implementation-defined. To ensure hashed +verification, always include a prefix such as {SHA256} (base64 digest) or use bcrypt.#!/bin/bash # Verify whether fallback is implemented in basicauth middleware FILES=$(fd -a 'middleware/.*/basicauth.*\.go$') echo "$FILES" rg -n -C2 'strings\.HasPrefix|SHA256|SHA512|bcrypt|hex\.DecodeString|base64\.StdEncoding\.DecodeString' $FILES
🧹 Nitpick comments (2)
docs/middleware/basicauth.md (2)
77-83: Good: correct OpenSSL commands (no trailing newline).
Consider adding a note that printf must not add a newline (avoid echo without -n).
98-98: Minor phrasing polish (optional).
“Next defines a function to skip this middleware when it returns true.” → “when it returns true” reads fine; no functional issue.-| Next | `func(fiber.Ctx) bool` | Next defines a function to skip this middleware when it returns true. | `nil` | +| Next | `func(fiber.Ctx) bool` | Next skips this middleware when the function returns true. | `nil` |
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
docs/middleware/basicauth.md(4 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
docs/**
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Review and update the contents of the
docsfolder if necessary when modifying code
Files:
docs/middleware/basicauth.md
🧠 Learnings (4)
📚 Learning: 2025-05-13T00:19:16.407Z
Learnt from: sixcolors
PR: gofiber/fiber#3446
File: docs/middleware/logger.md:44-44
Timestamp: 2025-05-13T00:19:16.407Z
Learning: In documentation files for the Fiber framework, code examples are often partial and don't repeat import statements that were shown in earlier examples, focusing instead on demonstrating specific usage patterns.
Applied to files:
docs/middleware/basicauth.md
📚 Learning: 2024-11-10T23:44:13.704Z
Learnt from: gaby
PR: gofiber/fiber#3193
File: middleware/adaptor/adaptor.go:111-111
Timestamp: 2024-11-10T23:44:13.704Z
Learning: In the `middleware/adaptor/adaptor.go` file of the Fiber framework, when updating context handling, replacing `c.Context()` with `c.RequestCtx()` is appropriate to access the `fasthttp.RequestCtx`.
Applied to files:
docs/middleware/basicauth.md
📚 Learning: 2025-05-15T12:56:45.397Z
Learnt from: mdelapenya
PR: gofiber/fiber#3434
File: services_test.go:450-464
Timestamp: 2025-05-15T12:56:45.397Z
Learning: The `New` function in the Fiber framework automatically calls `startServices` at initialization time when services are configured, making explicit calls to `startServices` unnecessary in code that creates an App instance with `New()`.
Applied to files:
docs/middleware/basicauth.md
📚 Learning: 2025-05-08T08:14:37.302Z
Learnt from: mdelapenya
PR: gofiber/fiber#3434
File: app.go:623-636
Timestamp: 2025-05-08T08:14:37.302Z
Learning: In the gofiber/fiber framework, service startup failures should panic rather than allowing the application to continue running with degraded functionality, as this is the agreed-upon design decision.
Applied to files:
docs/middleware/basicauth.md
🪛 LanguageTool
docs/middleware/basicauth.md
[grammar] ~74-~74: There might be a mistake here.
Context: ...base64, and prefix it with {SHA256} or {SHA512} before adding it to Users: ...
(QB_NEW_EN)
[grammar] ~98-~98: There might be a mistake here.
Context: ... | nil | | Users | map[string]string ...
(QB_NEW_EN)
🔇 Additional comments (10)
docs/middleware/basicauth.md (10)
7-7: Good: concise, accurate summary of behavior.
20-20: Good: import section clarifies required packages.
29-29: Good: sets clear usage flow after app init.
66-68: Good: prefix-based hash formats are clearly documented.
72-76: Good: clearer heading and instruction about base64-encoded digests.
85-92: Good: example hashes now match the shown “secret” commands.
13-16: Documentation signatures match implementation. No changes required.
102-104: All new Config fields (HeaderLimit, Authorizer, Unauthorized) and their defaults are present and correctly wired inconfig.go.
109-117: Defaults in docs match code
Documented defaults (Realm "Restricted", Charset "UTF-8", HeaderLimit 8192, implicit nil Authorizer/Unauthorized) align withConfigDefaultinmiddleware/basicauth/config.go.
32-41: Verified example hashes
SHA-256 for “doe” and bcrypt for “123456” both match the values in the docs—no changes needed.
|
/gemini review |
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you open a pull request for review, mark a draft as ready, or comment "@codex review". If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex fix this CI failure" or "@codex address that feedback". |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review
This pull request provides a comprehensive audit of the documentation, resulting in significant improvements to clarity, conciseness, and correctness across numerous files. The changes consistently enhance readability by rephrasing sentences, fixing typos, and improving code examples to align with best practices. The overall quality of the documentation is substantially elevated, and I have no further suggestions for improvement. Excellent work.
|
@ReneWerner87 agents cant find anything else |
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Summary