Skip to content
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: Improve ctx.Locals method description and example #3030

Merged
merged 1 commit into from
Jun 11, 2024

Conversation

sixcolors
Copy link
Member

@sixcolors sixcolors commented Jun 10, 2024

Description

Improve the ctx.Locals documentation to clarify the behavior of stored variables and their lifecycle to avoid unintentional resource closures, and provide best practices with keys and values.

Changes Introduced

  • Documentation Update:
    • Added a clarification that stored variables are removed after the request is handled.
    • Specified that if any stored data implements the io.Closer interface, its Close method will be called before it's removed.
  • Example Code Enhancement:
    • Demonstrated the use of a non-exported type as a key to avoid collisions.
    • Included type assertions when retrieving stored data to ensure it is of the expected type.

Details

  • File Modified: docs/api/ctx.md
  • Benchmark Impact: None
  • Documentation Updates: Improved clarity and provided best practices in the Locals method documentation.
  • Changelog Entries:
    • Clarified behavior of ctx.Locals regarding variable removal and io.Closer interface handling.
    • Updated example code to illustrate best practices for key usage and type assertions.
  • Migration Guide: Not applicable

These changes aim to prevent issues with unintentional resource closures, such as database connections, and enhance the clarity and safety of using ctx.Locals in fasthttp.

Copy link
Contributor

coderabbitai bot commented Jun 10, 2024

Walkthrough

The update enhances Fiber's Ctx object to store request-scoped variables, ensuring data is only available to matching routes. It introduces automatic removal of stored data after request processing and calls Close for data implementing io.Closer. The update emphasizes using type assertions for data retrieval and non-exported types as keys to prevent collisions.

Changes

File(s) Change Summary
docs/api/ctx.md Updated Locals function to handle variable removal post-request, call Close for io.Closer data, and use type assertions. Introduced non-exported types as keys to prevent collisions. Added examples for storing and retrieving data.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant FiberApp
    participant Ctx
    participant Handler

    User->>FiberApp: Send Request
    FiberApp->>Ctx: Store variable with Locals(key, value)
    FiberApp->>Handler: Process Request
    Handler->>Ctx: Retrieve variable with Locals(key)
    Handler->>FiberApp: Return Response
    FiberApp->>Ctx: Remove stored variable and call Close if io.Closer
    Ctx->>FiberApp: Confirm Cleanup
    FiberApp->>User: Send Response
Loading

Poem

In Fiber's heart, a change so neat,
Request-scoped vars, a tidy feat.
With keys unshared, collisions flee,
Data stored and cleaned with glee.
Type assertions, safe and sound,
In Fiber's world, new paths are found.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@sixcolors sixcolors marked this pull request as ready for review June 10, 2024 14:49
Copy link
Contributor

@coderabbitai coderabbitai bot left a 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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 6c3eb80 and c1c1278.

Files selected for processing (1)
  • docs/api/ctx.md (1 hunks)
Additional context used
LanguageTool
docs/api/ctx.md

[uncategorized] ~242-~242: Possible missing article found. (AI_HYDRA_LEO_MISSING_THE)
Context: ...aw()) // []byte("user=john") }) ``` > _Returned value is only valid within the handler....


[uncategorized] ~262-~262: Possible missing article found. (AI_HYDRA_LEO_MISSING_THE)
Context: ...dy()) // []byte("user=john") }) ``` > _Returned value is only valid within the handler....


[uncategorized] ~316-~316: Possible missing article found. (AI_HYDRA_LEO_MISSING_THE)
Context: ...lhost:3000/?name=john&pass=doe" ``` > _Returned value is only valid within the handler....


[style] ~373-~373: Consider a shorter alternative to avoid wordiness. (IN_ORDER_TO_PREMIUM)
Context: ... information from a ClientHello message in order to guide application logic in the GetCerti...


[typographical] ~396-~396: Consider adding a comma here. (PLEASE_COMMA)
Context: ...text() *fasthttp.RequestCtx ``` :::info Please read the [Fasthttp Documentation](https...


[uncategorized] ~486-~486: Possible missing article found. (AI_HYDRA_LEO_MISSING_THE)
Context: ...y", "doe") // "doe" // ... }) ``` > _Returned value is only valid within the handler....


[uncategorized] ~576-~576: Possible missing article found. (AI_HYDRA_LEO_MISSING_THE)
Context: ... or "" if not exist // .. }) ``` > _Returned value is only valid within the handler....


[uncategorized] ~581-~581: Use a comma before “and” if it connects two independent clauses (unless they are closely connected and short). (COMMA_COMPOUND_SENTENCE_2)
Context: ...icate that the client cache is now stale and the full response should be sent. When...


[uncategorized] ~612-~612: Possible missing article found. (AI_HYDRA_LEO_MISSING_THE)
Context: ..., "john") // "john" // .. }) ``` > _Returned value is only valid within the handler....


[uncategorized] ~623-~623: Possible missing article found. (AI_HYDRA_LEO_MISSING_THE)
Context: ...eqHeaders() map[string][]string ``` > _Returned value is only valid within the handler....


[uncategorized] ~647-~647: Possible missing article found. (AI_HYDRA_LEO_MISSING_THE)
Context: ..., "john") // "john" // .. }) ``` > _Returned value is only valid within the handler....


[uncategorized] ~658-~658: Possible missing article found. (AI_HYDRA_LEO_MISSING_THE)
Context: ...spHeaders() map[string][]string ``` > _Returned value is only valid within the handler....


[uncategorized] ~704-~704: Possible missing article found. (AI_HYDRA_LEO_MISSING_THE)
Context: ...() // "google.com" // ... }) ``` > _Returned value is only valid within the handler....


[uncategorized] ~1051-~1051: Possible missing article found. (AI_HYDRA_LEO_MISSING_THE)
Context: ...earch?q=something" // ... }) ``` > _Returned value is only valid within the handler....


[uncategorized] ~1055-~1055: Possible missing article found. (AI_HYDRA_LEO_MISSING_THE)
Context: ...e..._](../#zero-allocation) ## Params Method can be used to get the route parameters...


[uncategorized] ~1100-~1100: Possible missing article found. (AI_HYDRA_LEO_MISSING_THE)
Context: ...f the first wildcard segment }) ``` > _Returned value is only valid within the handler....


[uncategorized] ~1104-~1104: Possible missing article found. (AI_HYDRA_LEO_MISSING_THE)
Context: ...._](../#zero-allocation) ## ParamsInt Method can be used to get an integer from the ...


[grammar] ~1191-~1191: Did you mean “are” or “were”? (SENT_START_NNS_IS)
Context: ..." // ... }) ``` ## Queries Queries is a function that returns an object conta...


[uncategorized] ~1277-~1277: Possible missing article found. (AI_HYDRA_LEO_MISSING_THE)
Context: ... "nike") // "nike" // ... }) ``` > _Returned value is only valid within the handler....


[typographical] ~1409-~1409: Consider adding a comma here. (PLEASE_COMMA)
Context: ...t" ``` :::info For more parser settings please look here Config :::...


[uncategorized] ~1503-~1503: Possible missing article found. (AI_HYDRA_LEO_MISSING_A)
Context: ...ects back to refer URL. It redirects to fallback URL if refer header doesn't exists, wit...


[uncategorized] ~1503-~1503: Possible missing article found. (AI_HYDRA_LEO_MISSING_A)
Context: ...er URL. It redirects to fallback URL if refer header doesn't exists, with specified s...


[grammar] ~1503-~1503: The auxiliary verb ‘do’ requires the base form of the verb. (DID_BASEFORM)
Context: ...to fallback URL if refer header doesn't exists, with specified status, a positive inte...


[uncategorized] ~1529-~1529: Did you mean: “By default,”? (BY_DEFAULT_COMMA)
Context: ... data and sends a text/html response. By default Render uses the default [**Go Templat...


[style] ~1529-~1529: To make your writing clearer, consider a more direct alternative. (TAKE_A_LOOK)
Context: ...want to use another View engine, please take a look at our [Template middleware](h...


[grammar] ~1537-~1537: Please check the verb form. (SHE_LIVE)
Context: ....string) error ``` ## Request Request return the [*fasthttp.Request](https://godoc....


[style] ~1537-~1537: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym. (ENGLISH_WORD_REPEAT_BEGINNING_RULE)
Context: ...Request Request return the [*fasthttp.Request](https://godoc.org/github.com/valyala/f...


[grammar] ~1587-~1587: Please check the verb form. (SHE_LIVE)
Context: ...s: shoe,hat" ``` ## Response Response return the [*fasthttp.Response](https://godoc...


[style] ~1587-~1587: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym. (ENGLISH_WORD_REPEAT_BEGINNING_RULE)
Context: ...sponse Response return the [*fasthttp.Response](https://godoc.org/github.com/valyala/f...


[uncategorized] ~1603-~1603: There should be no space here. (EG_SPACE)
Context: ...y be helpful after overriding the path, i. e. an internal redirect. Note that handler...


[uncategorized] ~1603-~1603: Possible missing comma found. (AI_HYDRA_LEO_MISSING_COMMA)
Context: ...t. Note that handlers might be executed again which could result in an infinite loop....


[uncategorized] ~1657-~1657: Possible missing article found. (AI_HYDRA_LEO_MISSING_THE)
Context: ... return err } } ``` ## SaveFile Method is used to save any multipart file ...


[uncategorized] ~1690-~1690: Possible missing article found. (AI_HYDRA_LEO_MISSING_THE)
Context: ...n err } }) ``` ## SaveFileToStorage Method is used to save any multipart file ...


[uncategorized] ~1794-~1794: Possible missing comma found. (AI_HYDRA_LEO_MISSING_COMMA)
Context: ...fo If the file contains an url specific character you have to escape it before passing th...

Markdownlint
docs/api/ctx.md

1201-1201: Column: 1 (MD010, no-hard-tabs)
Hard tabs


1202-1202: Column: 1 (MD010, no-hard-tabs)
Hard tabs


1203-1203: Column: 1 (MD010, no-hard-tabs)
Hard tabs


1204-1204: Column: 1 (MD010, no-hard-tabs)
Hard tabs


1205-1205: Column: 1 (MD010, no-hard-tabs)
Hard tabs


1213-1213: Column: 1 (MD010, no-hard-tabs)
Hard tabs


1214-1214: Column: 1 (MD010, no-hard-tabs)
Hard tabs


1215-1215: Column: 1 (MD010, no-hard-tabs)
Hard tabs


1223-1223: Column: 1 (MD010, no-hard-tabs)
Hard tabs


1224-1224: Column: 1 (MD010, no-hard-tabs)
Hard tabs


1225-1225: Column: 1 (MD010, no-hard-tabs)
Hard tabs


1226-1226: Column: 1 (MD010, no-hard-tabs)
Hard tabs


1234-1234: Column: 1 (MD010, no-hard-tabs)
Hard tabs


1235-1235: Column: 1 (MD010, no-hard-tabs)
Hard tabs


1236-1236: Column: 1 (MD010, no-hard-tabs)
Hard tabs


1244-1244: Column: 1 (MD010, no-hard-tabs)
Hard tabs


1245-1245: Column: 1 (MD010, no-hard-tabs)
Hard tabs


1246-1246: Column: 1 (MD010, no-hard-tabs)
Hard tabs


1247-1247: Column: 1 (MD010, no-hard-tabs)
Hard tabs


1248-1248: Column: 1 (MD010, no-hard-tabs)
Hard tabs


1249-1249: Column: 1 (MD010, no-hard-tabs)
Hard tabs


1298-1298: Column: 1 (MD010, no-hard-tabs)
Hard tabs


1399-1399: Column: 1 (MD010, no-hard-tabs)
Hard tabs

Additional comments not posted (1)
docs/api/ctx.md (1)

903-924: The documentation and example for ctx.Locals method have been significantly improved to enhance clarity and prevent common mistakes like unintentional resource closures. The addition of type assertions and the use of non-exported types as keys are best practices that help avoid potential runtime errors and key collisions, respectively. These changes align well with the PR's objectives to enhance clarity and safety in using ctx.Locals.

@ReneWerner87 ReneWerner87 merged commit 6c9510d into v2 Jun 11, 2024
2 checks passed
@sixcolors sixcolors deleted the docs-ctx-io.Closer branch June 11, 2024 18:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants