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

🔥 Feature: Add Req and Res API #2894

Open
wants to merge 7 commits into
base: main
Choose a base branch
from

Conversation

nickajacks1
Copy link
Member

@nickajacks1 nickajacks1 commented Mar 3, 2024

CURRENT STATUS

  • Response
    • Ctx.Request => Ctx.Req
    • Complete fiber.Request API
    • Create Request Interface with a DefaultRequest implementation
    • Create Doc Page
  • Response API
    • Ctx.Response => Ctx.Res
    • Complete fiber.Response API
    • Create Response Interface with a DefaultResponse implementation
    • Create Doc Page

Description

Split the existing Ctx API into two separate APIs for Requests and Responses. Having distinct APIs for Request and Response types will allow developers to more easily write self-documenting code by avoiding ambiguous methods such as Ctx.Cookie and Ctx.Cookies. Much of the existing Ctx API simply calls the corresponding Req or Res API. For example, Ctx.Get calls Request.Get and Ctx.Set calls Response.Set.

Because Express defines only res and req APIs with no context API, this change will make it easier to manage Fiber's adherence to Express's APIs. In addition, it will allow us to avoid needing to create certain one-off methods. For example, Ctx.GetRespHeader can now become Ctx.Res().Get

Although the majority of the Ctx API is unchanged, Ctx.Request and Ctx.Response have been removed in favor of Ctx.Req and Ctx.Res. Now, instead of a raw fasthttp.Request or fasthttp.Response, we return fiber.Request and fiber.Response objects, which implement their respective APIs. As such, this is a breaking change for users who access Ctx.Request and Ctx.Response direct.

Inspired by Koa and fasthttp, both of which have individual request/response objects and a single context object whose methods are simply aliases for corresponding methods on the req/res APIs.

Deprecation:

  • Ctx.GetRespHeader is replaced by Ctx.Res().Get

Related to #2854

Changes introduced

List the new features or adjustments introduced in this pull request. Provide details on benchmarks, documentation updates, changelog entries, and if applicable, the migration guide.

  • Benchmarks: Describe any performance benchmarks and improvements related to the changes.
  • Documentation Update: Detail the updates made to the documentation and links to the changed files.
  • Changelog/What's New: Include a summary of the additions for the upcoming release notes.
  • Migration Guide: If necessary, provide a guide or steps for users to migrate their existing code to accommodate these changes.
  • API Alignment with Express: Explain how the changes align with the Express API.
  • API Longevity: Discuss the steps taken to ensure that the new or updated APIs are consistent and not prone to breaking changes.
  • Examples: Provide examples demonstrating the new features or changes in action.

Type of change

Please delete options that are not relevant.

  • New feature (non-breaking change which adds functionality)
  • Enhancement (improvement to existing features and functionality)
  • Documentation update (changes to documentation)
  • Performance improvement (non-breaking change which improves efficiency)
  • Code consistency (non-breaking change which improves code reliability and robustness)

Checklist

Before you submit your pull request, please make sure you meet these requirements:

  • Followed the inspiration of the Express.js framework for new functionalities, making them similar in usage.
  • Conducted a self-review of the code and provided comments for complex or critical parts.
  • Updated the documentation in the /docs/ directory for Fiber's documentation.
  • Added or updated unit tests to validate the effectiveness of the changes or new features.
  • Ensured that new and existing unit tests pass locally with the changes.
  • Verified that any new dependencies are essential and have been agreed upon by the maintainers/community.
  • Aimed for optimal performance with minimal allocations in the new code.
  • Provided benchmarks for the new code to analyze and improve upon.

Copy link
Contributor

coderabbitai bot commented Mar 3, 2024

Walkthrough

The updates introduce modifications to the DefaultCtx struct within the fiber package, adding new fields for request and response handling. New methods Req() and Res() facilitate access to these fields. Additionally, the NewDefaultCtx function is updated to initialize these fields. New structs DefaultReq and DefaultRes are introduced, each containing multiple methods that delegate functionality to the underlying context. Corresponding interfaces Req and Res are also defined, encapsulating request and response functionalities.

Changes

Files Summary of Changes
ctx.go, ctx_interface.go, ctx_interface_gen.go Added fields req and res to DefaultCtx, implemented methods Req() and Res(), and updated NewDefaultCtx.
req.go, req_interface_gen.go Introduced DefaultReq struct with multiple methods for handling HTTP request data and defined a corresponding Req interface.
res.go, res_interface_gen.go Introduced DefaultRes struct with various response handling methods and defined a corresponding Res interface.
ctx_test.go Updated test methods to replace direct context calls with calls to Req() and Res() methods for improved clarity.
docs/api/ctx.md Restructured and renamed several context methods, removing outdated methods and introducing new ones for better functionality.

Possibly related PRs

  • 🔥 Feature (v3): Add buffered streaming support #3131: The changes in the main PR, which involve adding new fields and methods to the DefaultCtx struct, are related to the modifications in the retrieved PR that also adds a new method to the same DefaultCtx struct, indicating a direct connection at the code level.
  • 🔥 feat: Add Context Support to RequestID Middleware #3200: The changes in the main PR, which involve adding fields and methods to the DefaultCtx struct for request and response handling, are related to the retrieved PR that modifies the requestid middleware to enhance context management by integrating the request ID into the fiber.Ctx object, as both involve modifications to the context structure and its methods.
  • 📚 Doc: Updates to Context documentation #3206: The changes in the main PR, which involve adding fields and methods to the DefaultCtx struct, are related to the modifications in the retrieved PR that update the documentation for the Ctx interface, as both pertain to the context handling in the fiber package.

Suggested reviewers

  • sixcolors
  • ReneWerner87
  • efectn

🐰✨
In the land of code where the bits align,
A rabbit hopped through, refactoring fine.
From request to response, through headers it weaved,
A tapestry of changes, expertly conceived.
Celebrate the craft, for improvements shine bright,
In the glow of the code, under the moonlight. 🌙
🌟🐇

✨ Finishing Touches
  • 📝 Generate Docstrings

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>, please review it.
    • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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 using 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 generate docstrings to generate docstrings for this 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.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration 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.

Copy link

codecov bot commented Mar 5, 2024

Codecov Report

Attention: Patch coverage is 29.92701% with 96 lines in your changes missing coverage. Please review.

Project coverage is 83.66%. Comparing base (6afba95) to head (64dd9bb).

Files with missing lines Patch % Lines
req.go 16.21% 62 Missing ⚠️
res.go 37.03% 34 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2894      +/-   ##
==========================================
- Coverage   84.29%   83.66%   -0.64%     
==========================================
  Files         116      118       +2     
  Lines       11572    11708     +136     
==========================================
+ Hits         9755     9795      +40     
- Misses       1389     1485      +96     
  Partials      428      428              
Flag Coverage Δ
unittests 83.66% <29.92%> (-0.64%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@gaby
Copy link
Member

gaby commented Mar 5, 2024

@nickajacks1 Just so you are aware, the tests are very unstable/flaky right now in main. This is because we no longer retry failed tests multiple times on the CI. This is being fixing in #2892

@nickajacks1
Copy link
Member Author

3/9: Moved some more methods from Ctx to Request. Rebased.

@nickajacks1
Copy link
Member Author

3/17: Rebase. Moved more trivial methods to Request.

@nickajacks1
Copy link
Member Author

Hi @gofiber/maintainers

Sorry this is taking so long.
I've reached the first major milestone - the Request API is fully moved over to the Request type.
I'd like to get a health check - does the overall direction still seem OK? If so, I suspect that moving the Response API over will be comparatively quick.
None of the unit tests have been moved over. IMO that's quite a bit of work and shouldn't hold up v3 since it's not public facing and can be done at any time.

@nickajacks1
Copy link
Member Author

Even though Express has Locals as part of the res API, I feel like it makes more sense to keep it as part of Ctx since it doesn't inherently have anything to do with the response (or request for that matter). I'm going to leave in Ctx for now.

@ReneWerner87
Copy link
Member

ok, sounds reasonable we can always adapt it later

@nickajacks1 nickajacks1 force-pushed the reqres branch 3 times, most recently from 31fde6b to d305ed8 Compare April 21, 2024 21:38
@nickajacks1
Copy link
Member Author

Ok, the Response API is fully moved over.

Some remaining work:
I didn't move Redirect to the Response API yet. The Redirect API has some dependencies on DefaultCtx that requires more thought. Moving Redirect to Res won't break the API in any way, so we can take our time thinking about this.

Next week I'll start on either the docs or the interface part.

@nickajacks1
Copy link
Member Author

I was thinking, is it actually that useful to make Request and Response interfaces if Ctx is already an interface and can thus be expanded instead of Request/Response? If we say that custom extensions should just go through Ctx, that might simplify both the API and implementation a bit.
Thoughts @gofiber/maintainers ?

@sixcolors
Copy link
Member

I was thinking, is it actually that useful to make Request and Response interfaces if Ctx is already an interface and can thus be expanded instead of Request/Response? If we say that custom extensions should just go through Ctx, that might simplify both the API and implementation a bit. Thoughts @gofiber/maintainers ?

I am interested in learning more about the approach of expanding the Ctx interface for custom extensions, instead of introducing separate Request and Response interfaces. Could you please explain how this approach works and how it simplifies the API for developers?

In addition, can you help us by merging the changes added to the main branch, and updating your PR to use the new Bind() interface?

Thank you, great work so far, and I look forward to your reply!

@nickajacks1
Copy link
Member Author

I am interested in learning more about the approach of expanding the Ctx interface for custom extensions, instead of introducing separate Request and Response interfaces. Could you please explain how this approach works and how it simplifies the API for developers?

The two primary points I have in mind are:

  1. Any extension of behavior can already be handled by using a custom Ctx since the split implementation is at its core a kind of syntactic sugar. I have not been able to think of a use case for Req/Res interfaces that can't be handled with the Ctx interface.
  2. Since the Ctx and Request+Response APIs have overlap, it may be less clear to developers which they should implement. If they want to update SendString to tee out some logs, should they do it by making a custom Ctx or a custom Respose? I feel like having either Ctx or Request+Response be interfaces may be more straightforward (and I lean toward Ctx). This is more what I meant when I implied that having all three of Ctx, Request, and Response be interfaces could make the API more complex.

In addition, can you help us by merging the changes added to the main branch, and updating your PR to use the new Bind() interface?

ye. will also probably be able to mark the PR ready for review soon.

@nickajacks1
Copy link
Member Author

nickajacks1 commented May 13, 2024

Marking as ready for review. If it is decided to make Request and Response interfaces, I will update the PR.
Regarding the docs, I think it might be better to get this in first and then write up the docs.

@nickajacks1 nickajacks1 marked this pull request as ready for review May 13, 2024 01:37
@nickajacks1 nickajacks1 requested a review from a team as a code owner May 13, 2024 01:37
@nickajacks1 nickajacks1 removed the request for review from a team May 13, 2024 01:37
* Sprinkle in calls to Req() and Res() to a few unit tests
* Fix improper initialization caught by ^
* Add a few missing methods
@nickajacks1
Copy link
Member Author

@ReneWerner87 this could probably be merged whenever

@ReneWerner87
Copy link
Member

Ok i will check it today, sorry lost focus last time

@ReneWerner87
Copy link
Member

@sixcolors @gaby @efectn let's recheck it so we can merge this big adjustment

@ReneWerner87
Copy link
Member

@nickajacks1 looks good to me, but can you please provide some more tests for the use of req/resp

@ReneWerner87
Copy link
Member

ReneWerner87 commented Feb 17, 2025

  • I had seen that you had customized the current ones, but I would find it better if you added additional ones
    so that the use with the direct use of req/res is tested and if you use it directly from the context object

  • performance technically, do we still need to create pools for the objects ? to minimize the allocations in the process and then reset them when clearing the context ?

@grivera64
Copy link
Member

Thanks for working on this PR! It will be quite useful for distinguishing between Request and Response-based methods in Ctx.

I have an idea that could help with this bulletpoint from above:

  • performance technically, do we still need to create pools for the objects ? to minimize the allocations in the process and then reset them when clearing the context ?

From reviewing the PR, could we theoretically use an interface for Req and Res instead of a dedicated struct to avoid allocations/clearing altogether (aside from the already done allocation/clearing for the DefaultCtx struct) for performance?

I'm not entirely sure if it’s idiomatic to do this in Go, but we could set up Ctx, Req, and Res like in the following example:

// All Req and Res-based methods
type Ctx interface {
  Queries() map[string]string
  SendString(body string) error
  // …
}

// Req - Request-based Ctx methods
type Req interface {
  Queries() map[string]string
  // …
}

// Res - Response-based Ctx methods
type Res interface {
  SendString(body string) error
  // …
}

We would need to look more into it, but this could potentially be autogenerated in the same way that Ctx is currently generated by ifacemaker. Then, all we would need is to rewrite (*DefaultCtx).Req() and (*DefaultCtx).Res() as:

func (c *DefaultCtx) Req() Req {
  return c
}

func (c *DefaultCtx) Res() Res {
  return c
}

If we do this, it should not allocate any new memory but rather cast the Ctx interface to a sub-interface for Req or Res. This would also eliminate the need to create any new methods for Req and Res directly when a new feature is added to Ctx.

If this idea wouldn't work well with this PR, I agree that we could also just add a pool for low memory footprint. I believe that and adding tests for the old and new v3 Ctx methods (e.g. c.SendStreamWriter()) would be all that is left before this is ready to merge.

Thanks again for the PR!

@ReneWerner87
Copy link
Member

@grivera64 in the first iteration i would like to go with this concept and after that you can show the new concept via pr or issue report
in the end, nothing should change in the usage, so that there is no breaking change, even if we do it in two steps

@ReneWerner87
Copy link
Member

@nickajacks1 are you working on the last comments ?

@nickajacks1
Copy link
Member Author

@ReneWerner87 Yes, I will work on this on Friday. Can you give a brief example of what kind of tests you would like to see

@ReneWerner87
Copy link
Member

the previous tests you changed in ctx should be reset and you should create test files for the req and resp struct that test the existing functions
similar to what happens in ctx

theoretically, the function used in the req or resp object could also contain additional code or a new method could exist
of course it is currently only forwarded, but we don't know what we plan to do with it in the future
every test should therefore test the function of the underlying method

it may also be that it is too much of a good thing, because we currently know that we are only forwarding, but theoretically you could also adjust the parameters and return in the respective wrapper methods so that it can be used better

@grivera64
Copy link
Member

@grivera64 in the first iteration i would like to go with this concept and after that you can show the new concept via pr or issue report in the end, nothing should change in the usage, so that there is no breaking change, even if we do it in two steps

For sure, sounds good to me! After this is merged, I can create an issue/PR with the new concept so we can discuss more about it.

@nickajacks1
Copy link
Member Author

I just realized how many tests there are 😁
I thought of some ways to do this

  1. Duplicate all tests for Req and Res
  2. Create smaller smoke tests for Req and Res that are more compact/not as thorough
  3. Somehow templatize the tests so that they end up in a format like
func testAccepts(t *testing.T, r Req) {}
func TestAccepts(t *testing.T) {
    app := New()
    c := app.AcquireCtx(&fasthttp.RequestCtx{})
    t.Run("ctx", func(t *testing.T) { testAccepts(t, c) })
    t.Run("req", func(t *testing.T) { testAccepts(t, c.Req()) })
}

what do folks think? 3 sounds potentially nice but would have a huge impact to the tests and be a lot of work and potentially increased cognitive overhead. 1 seems overkill and prone to subtle drift unless the duplicated tests were generated somehow. 2 seems reasonable to me.

By the way, even with these changes, there are no additional allocations (I checked Benchmark_Ctx_AcquireReleaseFlow). That said, I kind of like @grivera64 's idea of simply having req and res be views onto the Ctx interface rather than bespoke objects.

@ReneWerner87
Copy link
Member

ReneWerner87 commented Feb 22, 2025

I like idea 2 and 3

Btw we also need to somehow duplicate the docs

  • Updated the documentation in the /docs/ directory for Fiber's documentation.

@nickajacks1
Copy link
Member Author

nickajacks1 commented Feb 24, 2025

Update: rearranged docs. Added some methods I missed. Have not added tests yet.
image

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: 1

♻️ Duplicate comments (1)
req.go (1)

9-11: 🛠️ Refactor suggestion

Validate ctx to avoid nil pointer dereferences.

Consider adding a constructor or an internal check to ensure ctx is not nil. Without this safeguard, dereferencing a nil ctx would lead to a runtime panic.

+// NewDefaultReq creates a new DefaultReq and validates the ctx parameter.
+func NewDefaultReq(ctx *DefaultCtx) *DefaultReq {
+    if ctx == nil {
+        panic("DefaultCtx cannot be nil")
+    }
+    return &DefaultReq{ctx: ctx}
+}
🧹 Nitpick comments (3)
res.go (1)

1-4: Group imports for better organization.

The imports should be grouped using parentheses for consistency.

-import "bufio"
+import (
+  "bufio"
+)
🧰 Tools
🪛 GitHub Check: lint

[failure] 3-3:
should only use grouped 'import' declarations (grouper)

docs/api/ctx.md (2)

288-288: Improve documentation readability and clarity.

Several minor improvements can enhance the documentation:

  1. Add missing commas in appropriate places:

    • After "Please read" in the Fasthttp Documentation section
    • After "Please use" in the TrustProxy section
  2. Remove redundant phrases:

    • Replace "outside of" with "outside"
    • Replace "in order to" with "to"
    • Replace "take a look at" with "see" or "refer to"
  3. Add missing articles:

    • Add "The" before "Method is used to save"
    • Add "The" before "Method is used to save" in SaveFileToStorage section
  4. Fix compound sentences:

    • Add a comma before "and" in compound sentences where appropriate

Also applies to: 316-316, 590-590, 672-672, 1237-1237, 1270-1270, 1308-1308, 1883-1883

🧰 Tools
🪛 LanguageTool

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

(PLEASE_COMMA)


1394-1584: Update cookie documentation to include security best practices.

The cookie documentation should include security best practices and recommendations for:

  • Setting secure flags
  • Using SameSite attribute
  • Handling HttpOnly cookies
  • Cookie expiration best practices
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2b891e8 and 0598cb0.

📒 Files selected for processing (5)
  • docs/api/ctx.md (30 hunks)
  • req.go (1 hunks)
  • req_interface_gen.go (1 hunks)
  • res.go (1 hunks)
  • res_interface_gen.go (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
docs/api/ctx.md (1)
Learnt from: gaby
PR: gofiber/fiber#3170
File: ctx.go:1825-1826
Timestamp: 2024-11-12T14:10:51.810Z
Learning: In the Fiber framework, the `IsProxyTrusted()` function returns `true` when `TrustProxy` is `false`, maintaining compatibility with version 2 behavior.
🪛 GitHub Check: codecov/patch
req.go

[warning] 17-18: req.go#L17-L18
Added lines #L17 - L18 were not covered by tests


[warning] 21-22: req.go#L21-L22
Added lines #L21 - L22 were not covered by tests


[warning] 25-26: req.go#L25-L26
Added lines #L25 - L26 were not covered by tests


[warning] 29-30: req.go#L29-L30
Added lines #L29 - L30 were not covered by tests


[warning] 33-34: req.go#L33-L34
Added lines #L33 - L34 were not covered by tests


[warning] 37-38: req.go#L37-L38
Added lines #L37 - L38 were not covered by tests


[warning] 41-42: req.go#L41-L42
Added lines #L41 - L42 were not covered by tests


[warning] 53-54: req.go#L53-L54
Added lines #L53 - L54 were not covered by tests


[warning] 57-58: req.go#L57-L58
Added lines #L57 - L58 were not covered by tests


[warning] 61-62: req.go#L61-L62
Added lines #L61 - L62 were not covered by tests


[warning] 65-66: req.go#L65-L66
Added lines #L65 - L66 were not covered by tests


[warning] 69-70: req.go#L69-L70
Added lines #L69 - L70 were not covered by tests


[warning] 77-78: req.go#L77-L78
Added lines #L77 - L78 were not covered by tests


[warning] 81-82: req.go#L81-L82
Added lines #L81 - L82 were not covered by tests


[warning] 89-90: req.go#L89-L90
Added lines #L89 - L90 were not covered by tests


[warning] 93-94: req.go#L93-L94
Added lines #L93 - L94 were not covered by tests


[warning] 97-98: req.go#L97-L98
Added lines #L97 - L98 were not covered by tests


[warning] 101-102: req.go#L101-L102
Added lines #L101 - L102 were not covered by tests


[warning] 105-106: req.go#L105-L106
Added lines #L105 - L106 were not covered by tests


[warning] 109-110: req.go#L109-L110
Added lines #L109 - L110 were not covered by tests


[warning] 113-114: req.go#L113-L114
Added lines #L113 - L114 were not covered by tests


[warning] 117-118: req.go#L117-L118
Added lines #L117 - L118 were not covered by tests


[warning] 125-126: req.go#L125-L126
Added lines #L125 - L126 were not covered by tests


[warning] 129-130: req.go#L129-L130
Added lines #L129 - L130 were not covered by tests


[warning] 133-134: req.go#L133-L134
Added lines #L133 - L134 were not covered by tests


[warning] 137-138: req.go#L137-L138
Added lines #L137 - L138 were not covered by tests


[warning] 141-142: req.go#L141-L142
Added lines #L141 - L142 were not covered by tests


[warning] 145-146: req.go#L145-L146
Added lines #L145 - L146 were not covered by tests


[warning] 149-150: req.go#L149-L150
Added lines #L149 - L150 were not covered by tests


[warning] 153-154: req.go#L153-L154
Added lines #L153 - L154 were not covered by tests

🪛 GitHub Check: lint
req.go

[failure] 109-109:
unused-parameter: parameter 'override' seems to be unused, consider removing or renaming it as _ (revive)

res.go

[failure] 3-3:
should only use grouped 'import' declarations (grouper)

🪛 GitHub Actions: golangci-lint
req.go

[warning] 109-109: unused-parameter: parameter 'override' seems to be unused, consider removing or renaming it as _ (revive)

🪛 LanguageTool
docs/api/ctx.md

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

(PLEASE_COMMA)


[style] ~316-~316: This phrase is redundant. Consider using “outside”.
Context: ...x *fasthttp.RequestCtx) ``` It is used outside of the Fiber Handlers to reset the context...

(OUTSIDE_OF)


[style] ~590-~590: Consider a shorter alternative to avoid wordiness.
Context: ... information from a ClientHello message in order to guide application logic in the `GetCert...

(IN_ORDER_TO_PREMIUM)


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

(COMMA_COMPOUND_SENTENCE_2)


[uncategorized] ~1237-~1237: Possible missing article found.
Context: ...0, 700] } } }) ``` ### SaveFile Method is used to save any multipart file ...

(AI_HYDRA_LEO_MISSING_THE)


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

(AI_HYDRA_LEO_MISSING_THE)


[typographical] ~1308-~1308: Consider adding a comma here.
Context: ...porhttps for TLS requests. :::info Please use [Config.TrustProxy`](fiber.md#trus...

(PLEASE_COMMA)


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

(TAKE_A_LOOK)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: unit (1.23.x, windows-latest)
  • GitHub Check: repeated
  • GitHub Check: Compare
🔇 Additional comments (5)
req_interface_gen.go (1)

1-49: Interface definition looks good.

This auto-generated interface file strictly declares method signatures without any implementation details. It appears consistent with the existing naming conventions in the fiber package. No immediate changes are required here, but consider ensuring corresponding doc comments are placed in upstream definitions if needed.

req.go (1)

13-159: Add unit tests to improve coverage.

Most of these delegating methods are not tested, as indicated by static analysis. While they simply wrap r.ctx calls, unit tests can confirm that each method delegates correctly, helping maintain stable and predictable behavior.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 17-18: req.go#L17-L18
Added lines #L17 - L18 were not covered by tests


[warning] 21-22: req.go#L21-L22
Added lines #L21 - L22 were not covered by tests


[warning] 25-26: req.go#L25-L26
Added lines #L25 - L26 were not covered by tests


[warning] 29-30: req.go#L29-L30
Added lines #L29 - L30 were not covered by tests


[warning] 33-34: req.go#L33-L34
Added lines #L33 - L34 were not covered by tests


[warning] 37-38: req.go#L37-L38
Added lines #L37 - L38 were not covered by tests


[warning] 41-42: req.go#L41-L42
Added lines #L41 - L42 were not covered by tests


[warning] 53-54: req.go#L53-L54
Added lines #L53 - L54 were not covered by tests


[warning] 57-58: req.go#L57-L58
Added lines #L57 - L58 were not covered by tests


[warning] 61-62: req.go#L61-L62
Added lines #L61 - L62 were not covered by tests


[warning] 65-66: req.go#L65-L66
Added lines #L65 - L66 were not covered by tests


[warning] 69-70: req.go#L69-L70
Added lines #L69 - L70 were not covered by tests


[warning] 77-78: req.go#L77-L78
Added lines #L77 - L78 were not covered by tests


[warning] 81-82: req.go#L81-L82
Added lines #L81 - L82 were not covered by tests


[warning] 89-90: req.go#L89-L90
Added lines #L89 - L90 were not covered by tests


[warning] 93-94: req.go#L93-L94
Added lines #L93 - L94 were not covered by tests


[warning] 97-98: req.go#L97-L98
Added lines #L97 - L98 were not covered by tests


[warning] 101-102: req.go#L101-L102
Added lines #L101 - L102 were not covered by tests


[warning] 105-106: req.go#L105-L106
Added lines #L105 - L106 were not covered by tests


[warning] 109-110: req.go#L109-L110
Added lines #L109 - L110 were not covered by tests


[warning] 113-114: req.go#L113-L114
Added lines #L113 - L114 were not covered by tests


[warning] 117-118: req.go#L117-L118
Added lines #L117 - L118 were not covered by tests


[warning] 125-126: req.go#L125-L126
Added lines #L125 - L126 were not covered by tests


[warning] 129-130: req.go#L129-L130
Added lines #L129 - L130 were not covered by tests


[warning] 133-134: req.go#L133-L134
Added lines #L133 - L134 were not covered by tests


[warning] 137-138: req.go#L137-L138
Added lines #L137 - L138 were not covered by tests


[warning] 141-142: req.go#L141-L142
Added lines #L141 - L142 were not covered by tests


[warning] 145-146: req.go#L145-L146
Added lines #L145 - L146 were not covered by tests


[warning] 149-150: req.go#L149-L150
Added lines #L149 - L150 were not covered by tests


[warning] 153-154: req.go#L153-L154
Added lines #L153 - L154 were not covered by tests

🪛 GitHub Check: lint

[failure] 109-109:
unused-parameter: parameter 'override' seems to be unused, consider removing or renaming it as _ (revive)

🪛 GitHub Actions: golangci-lint

[warning] 109-109: unused-parameter: parameter 'override' seems to be unused, consider removing or renaming it as _ (revive)

res_interface_gen.go (1)

1-39: Interface definition looks consistent.

This auto-generated interface file cleanly outlines the response API. Ensure updates to the underlying implementation in DefaultRes remain in sync, and verify that doc comments for these methods exist in upstream definitions if needed.

res.go (2)

5-8: LGTM! Well-structured struct definition.

The DefaultRes struct follows good design practices with proper encapsulation and clear naming. The go:generate directive ensures proper interface generation.


10-117: Add unit tests for response API methods.

The response API methods lack test coverage. This is critical for ensuring the delegation pattern works correctly and maintaining reliability during future changes.

Would you like me to help generate comprehensive unit tests for these methods?

Consider standardizing return types across methods.

Some methods return Ctx (e.g., Status, Type) while others return error. Consider standardizing the return types for better consistency and predictability.

For example:

-func (r *DefaultRes) Status(status int) Ctx {
+func (r *DefaultRes) Status(status int) error {
   return r.ctx.Status(status)
}

-func (r *DefaultRes) Type(extension string, charset ...string) Ctx {
+func (r *DefaultRes) Type(extension string, charset ...string) error {
   return r.ctx.Type(extension, charset...)
}

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: 2

♻️ Duplicate comments (1)
req.go (1)

109-111: ⚠️ Potential issue

Remove unused parameter override from Path method.

The override parameter is declared but never used in the Path method.

Apply this diff:

-func (r *DefaultReq) Path(override ...string) string {
+func (r *DefaultReq) Path() string {
 	return r.ctx.Path()
 }
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 109-110: req.go#L109-L110
Added lines #L109 - L110 were not covered by tests

🧹 Nitpick comments (1)
res.go (1)

1-119: Add unit tests for the response API methods.

The static analysis indicates that the new response API methods lack test coverage. This is critical for ensuring the delegation pattern works correctly and maintaining reliability during future changes.

Would you like me to help generate comprehensive unit tests for these methods?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0598cb0 and bb91f32.

📒 Files selected for processing (4)
  • req.go (1 hunks)
  • req_interface_gen.go (1 hunks)
  • res.go (1 hunks)
  • res_interface_gen.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • req_interface_gen.go
  • res_interface_gen.go
🧰 Additional context used
🪛 GitHub Check: codecov/patch
req.go

[warning] 17-18: req.go#L17-L18
Added lines #L17 - L18 were not covered by tests


[warning] 21-22: req.go#L21-L22
Added lines #L21 - L22 were not covered by tests


[warning] 25-26: req.go#L25-L26
Added lines #L25 - L26 were not covered by tests


[warning] 29-30: req.go#L29-L30
Added lines #L29 - L30 were not covered by tests


[warning] 33-34: req.go#L33-L34
Added lines #L33 - L34 were not covered by tests


[warning] 37-38: req.go#L37-L38
Added lines #L37 - L38 were not covered by tests


[warning] 41-42: req.go#L41-L42
Added lines #L41 - L42 were not covered by tests


[warning] 53-54: req.go#L53-L54
Added lines #L53 - L54 were not covered by tests


[warning] 57-58: req.go#L57-L58
Added lines #L57 - L58 were not covered by tests


[warning] 61-62: req.go#L61-L62
Added lines #L61 - L62 were not covered by tests


[warning] 65-66: req.go#L65-L66
Added lines #L65 - L66 were not covered by tests


[warning] 69-70: req.go#L69-L70
Added lines #L69 - L70 were not covered by tests


[warning] 77-78: req.go#L77-L78
Added lines #L77 - L78 were not covered by tests


[warning] 81-82: req.go#L81-L82
Added lines #L81 - L82 were not covered by tests


[warning] 89-90: req.go#L89-L90
Added lines #L89 - L90 were not covered by tests


[warning] 93-94: req.go#L93-L94
Added lines #L93 - L94 were not covered by tests


[warning] 97-98: req.go#L97-L98
Added lines #L97 - L98 were not covered by tests


[warning] 101-102: req.go#L101-L102
Added lines #L101 - L102 were not covered by tests


[warning] 105-106: req.go#L105-L106
Added lines #L105 - L106 were not covered by tests


[warning] 109-110: req.go#L109-L110
Added lines #L109 - L110 were not covered by tests


[warning] 113-114: req.go#L113-L114
Added lines #L113 - L114 were not covered by tests


[warning] 117-118: req.go#L117-L118
Added lines #L117 - L118 were not covered by tests


[warning] 125-126: req.go#L125-L126
Added lines #L125 - L126 were not covered by tests


[warning] 129-130: req.go#L129-L130
Added lines #L129 - L130 were not covered by tests


[warning] 133-134: req.go#L133-L134
Added lines #L133 - L134 were not covered by tests


[warning] 137-138: req.go#L137-L138
Added lines #L137 - L138 were not covered by tests


[warning] 141-142: req.go#L141-L142
Added lines #L141 - L142 were not covered by tests


[warning] 145-146: req.go#L145-L146
Added lines #L145 - L146 were not covered by tests


[warning] 149-150: req.go#L149-L150
Added lines #L149 - L150 were not covered by tests


[warning] 153-154: req.go#L153-L154
Added lines #L153 - L154 were not covered by tests

⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: unit (1.23.x, macos-13)
  • GitHub Check: unit (1.23.x, windows-latest)
  • GitHub Check: repeated
  • GitHub Check: Compare
  • GitHub Check: Analyse
🔇 Additional comments (2)
req.go (2)

9-11: Add validation for ctx field.

The DefaultReq struct should validate that the ctx field is not nil during initialization to prevent potential panics.


1-160: Add unit tests for the request API methods.

The static analysis indicates that the new request API methods lack test coverage. Comprehensive testing is essential for validating the delegation behavior.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 17-18: req.go#L17-L18
Added lines #L17 - L18 were not covered by tests


[warning] 21-22: req.go#L21-L22
Added lines #L21 - L22 were not covered by tests


[warning] 25-26: req.go#L25-L26
Added lines #L25 - L26 were not covered by tests


[warning] 29-30: req.go#L29-L30
Added lines #L29 - L30 were not covered by tests


[warning] 33-34: req.go#L33-L34
Added lines #L33 - L34 were not covered by tests


[warning] 37-38: req.go#L37-L38
Added lines #L37 - L38 were not covered by tests


[warning] 41-42: req.go#L41-L42
Added lines #L41 - L42 were not covered by tests


[warning] 53-54: req.go#L53-L54
Added lines #L53 - L54 were not covered by tests


[warning] 57-58: req.go#L57-L58
Added lines #L57 - L58 were not covered by tests


[warning] 61-62: req.go#L61-L62
Added lines #L61 - L62 were not covered by tests


[warning] 65-66: req.go#L65-L66
Added lines #L65 - L66 were not covered by tests


[warning] 69-70: req.go#L69-L70
Added lines #L69 - L70 were not covered by tests


[warning] 77-78: req.go#L77-L78
Added lines #L77 - L78 were not covered by tests


[warning] 81-82: req.go#L81-L82
Added lines #L81 - L82 were not covered by tests


[warning] 89-90: req.go#L89-L90
Added lines #L89 - L90 were not covered by tests


[warning] 93-94: req.go#L93-L94
Added lines #L93 - L94 were not covered by tests


[warning] 97-98: req.go#L97-L98
Added lines #L97 - L98 were not covered by tests


[warning] 101-102: req.go#L101-L102
Added lines #L101 - L102 were not covered by tests


[warning] 105-106: req.go#L105-L106
Added lines #L105 - L106 were not covered by tests


[warning] 109-110: req.go#L109-L110
Added lines #L109 - L110 were not covered by tests


[warning] 113-114: req.go#L113-L114
Added lines #L113 - L114 were not covered by tests


[warning] 117-118: req.go#L117-L118
Added lines #L117 - L118 were not covered by tests


[warning] 125-126: req.go#L125-L126
Added lines #L125 - L126 were not covered by tests


[warning] 129-130: req.go#L129-L130
Added lines #L129 - L130 were not covered by tests


[warning] 133-134: req.go#L133-L134
Added lines #L133 - L134 were not covered by tests


[warning] 137-138: req.go#L137-L138
Added lines #L137 - L138 were not covered by tests


[warning] 141-142: req.go#L141-L142
Added lines #L141 - L142 were not covered by tests


[warning] 145-146: req.go#L145-L146
Added lines #L145 - L146 were not covered by tests


[warning] 149-150: req.go#L149-L150
Added lines #L149 - L150 were not covered by tests


[warning] 153-154: req.go#L153-L154
Added lines #L153 - L154 were not covered by tests

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

🔭 Outside diff range comments (2)
ctx.go (2)

1912-1929: 🛠️ Refactor suggestion

Initialize req and res fields in the Reset method

The Reset method is used to reset context fields when reusing a context object, but it doesn't initialize the req and res fields. This could lead to unexpected behavior if these fields are accessed after a reset.

// Reset is a method to reset context fields by given request when to use server handlers.
func (c *DefaultCtx) Reset(fctx *fasthttp.RequestCtx) {
  // Reset route and handler index
  c.indexRoute = -1
  c.indexHandler = 0
  // Reset matched flag
  c.matched = false
  // Set paths
  c.pathOriginal = c.app.getString(fctx.URI().PathOriginal())
  // Set method
  c.method = c.app.getString(fctx.Request.Header.Method())
  c.methodINT = c.app.methodInt(c.method)
  // Attach *fasthttp.RequestCtx to ctx
  c.fasthttp = fctx
  // reset base uri
  c.baseURI = ""
+ // Reset req and res fields
+ if c.req != nil {
+   c.req.c = c
+ }
+ if c.res != nil {
+   c.res.c = c
+ }
  // Prettify path
  c.configDependentPaths()
}

1932-1942: 🛠️ Refactor suggestion

Release req and res fields in the release method

The release method cleans up resources when a context is released back to the pool, but it doesn't handle the req and res fields. These should be properly released to avoid memory leaks.

// Release is a method to reset context fields when to use ReleaseCtx()
func (c *DefaultCtx) release() {
  c.route = nil
  c.fasthttp = nil
  c.bind = nil
+ c.req = nil
+ c.res = nil
  c.flashMessages = c.flashMessages[:0]
  c.viewBindMap = sync.Map{}
  if c.redirect != nil {
    ReleaseRedirect(c.redirect)
    c.redirect = nil
  }
}
🧹 Nitpick comments (1)
ctx.go (1)

474-476: Consider adding deprecation notices to Request() and Response() methods

Since you're introducing Req() and Res() methods as replacements for Request() and Response(), you should consider adding deprecation notices to the old methods to guide users toward the new API.

// Request return the *fasthttp.Request object
// This allows you to use all fasthttp request methods
// https://godoc.org/github.com/valyala/fasthttp#Request
+// Deprecated: Use Req() instead which provides a more comprehensive API.
func (c *DefaultCtx) Request() *fasthttp.Request {
  return &c.fasthttp.Request
}

// Response return the *fasthttp.Response object
// This allows you to use all fasthttp response methods
// https://godoc.org/github.com/valyala/fasthttp#Response
+// Deprecated: Use Res() instead which provides a more comprehensive API.
func (c *DefaultCtx) Response() *fasthttp.Response {
  return &c.fasthttp.Response
}

Also applies to: 481-483

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bb91f32 and 64dd9bb.

📒 Files selected for processing (2)
  • ctx.go (2 hunks)
  • ctx_test.go (17 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: unit (1.24.x, macos-13)
  • GitHub Check: unit (1.24.x, macos-latest)
  • GitHub Check: unit (1.24.x, windows-latest)
  • GitHub Check: unit (1.23.x, macos-13)
  • GitHub Check: unit (1.23.x, macos-latest)
  • GitHub Check: unit (1.23.x, windows-latest)
  • GitHub Check: repeated
  • GitHub Check: Compare
🔇 Additional comments (16)
ctx.go (3)

57-58: LGTM: New fields for request and response APIs

The addition of req and res fields to the DefaultCtx struct correctly implements the PR objective of splitting the Ctx API into separate request and response APIs.


1468-1472: Fix documentation comment for Req() method

The documentation comment correctly describes the purpose of the Req() method, returning a convenience type limited to operations on the incoming request.

However, there's a need for test coverage to ensure this method works properly.

Looking at the previous comments, there's no direct test coverage for this method. Please add a unit test to verify:

  1. The method returns the internal req field
  2. The returned value implements the Req interface
  3. Operations on the returned object affect the context's request

1474-1478: Add test coverage for the Res() method

The implementation and documentation for the Res() method are clear and correct. However, as noted in previous code reviews, this method lacks test coverage.

Please add unit tests to ensure that:

  1. The method returns the internal res field
  2. The returned value implements the Res interface
  3. Operations on the returned value affect the context's response
ctx_test.go (13)

49-49: API restructuring: Methods migrated to Req() interface

The change reflects the intended separation of concerns by moving request-related functionality from the context to the new Req API. This improves clarity and aligns with the PR objectives of splitting the Ctx API.

Also applies to: 60-60, 66-66


971-1010: API restructuring: Cookie management moved to Res() interface

Cookie management functions have been properly moved to the response object. This change is consistent with the architectural changes described in the PR objectives and helps clarify responsibility boundaries.


1036-1037: API restructuring: Cookie retrieval moved to Req() interface

Cookie retrieval from the request has been properly moved to the new Req API. This separation of request/response concerns improves API clarity and matches the PR goals.


1061-1062: API restructuring: Content negotiation moved to Res() interface

Content format negotiation functions have been moved to the response object, which is appropriate as they determine the format of the response. This change is consistent with the architectural goals.

Also applies to: 1067-1068


1168-1168: API restructuring: AutoFormat methods moved to Res() interface

The AutoFormat methods have been relocated to the response object, which is a logical placement as they handle response content formatting.

Also applies to: 1178-1178


1785-1789: API restructuring: JSONP response moved to Res() interface

JSONP functionality has been appropriately moved to the response interface as it deals with response formatting.


2942-2942: API restructuring: FormFile moved to Req() interface

The FormFile method has been correctly relocated to the request interface since it retrieves files from the request.


3078-3078: API restructuring: ClearCookie moved to Res() interface

Cookie clearing operations have been moved to the response interface, which is appropriate since setting cookies is part of the response.


3107-3107: API restructuring: File operations moved to Res() interface

File download and sending operations have been moved to the response interface, which makes sense as they generate response content.

Also applies to: 3139-3139, 3164-3164


4009-4009: API restructuring: Render moved to Res() interface

The template rendering function has been appropriately moved to the response interface, as it generates response content.


4910-4910: API restructuring: Query handling moved to Req() interface

Query parameter handling has been correctly moved to the request interface, as it deals with extracting data from the request.


5058-5058: API restructuring: IP and locality checks moved to Req() interface

Methods for checking client IP address and whether requests are from localhost have been appropriately moved to the request interface.

Also applies to: 5091-5092


1-7060: Overall implementation aligns with PR objectives

The changes in this file demonstrate a consistent implementation of the architectural refactoring described in the PR objectives. The separation of Ctx into Req and Res APIs improves clarity by making it explicit which operations apply to requests versus responses. The test suite has been thoroughly updated to use the new API structure.

@gaby
Copy link
Member

gaby commented Mar 2, 2025

@nickajacks1 What is left to-do here?

@nickajacks1
Copy link
Member Author

@gaby
Only thing left is smoke-test type unit tests for the new interfaces. IMO this could be merged without the tests, but I'm still working on getting that part done.

@gaby
Copy link
Member

gaby commented Mar 2, 2025

@nickajacks1 agree my browser freezes when I open this PR 😂😂😂

@ReneWerner87
Copy link
Member

definitely thanks for the PR

  • an update with the current master code would still be good
  • documentation markdown files

documentation is also missing

@nickajacks1
Copy link
Member Author

@ReneWerner87 I updated ctx.md and reordered the methods into Request and Response subsections, let me know what you think

@ReneWerner87
Copy link
Member

https://github.com/gofiber/fiber/pull/2894/files#diff-eed7ea7ab33c80ec8dfbd395f659cc34525831b8553a4c8737064a9b8d8e0e34

think we should not reduce the ctx.md, because you can also use this function directly
the use via the request and response object is additional

what do you think ? @gaby @efectn

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.

📝 [v3 Proposal]: Koa Style ctx.Request and ctx.Response Objects
7 participants