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

🩹 Fix: static server in sub app with mount (#3104) #3132

Open
wants to merge 1 commit into
base: v2
Choose a base branch
from

Conversation

yinheli
Copy link
Contributor

@yinheli yinheli commented Sep 14, 2024

Description

This commit fixes an issue with static file serving in sub-app when using the Mount method. The problem was that static routes in sub-apps were not being properly handled when the sub-app was mounted to a parent app.

Key changes:

  1. Modified the PathRewrite function in router.go to handle mount paths correctly for static file serving.
  2. Updated the Test_Route_Static_SubApp test in router_test.go to include a nested sub-app scenario.
  3. Added assertions to verify correct static file serving in both sub-app and nested sub-app cases.

Fixes #3104

Changes introduced

  • Examples:
    parentApp := fiber.New()
    subApp := fiber.New()
    
    subApp.Static("/public", "./public")
    parentApp.Mount("/sub", subApp)
    
    // Now, "/sub/public/*" will correctly serve static files from the "./public" directory

Type of change

  • Enhancement (improvement to existing features and functionality)

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.

@yinheli yinheli requested a review from a team as a code owner September 14, 2024 15:20
@yinheli yinheli requested review from gaby, sixcolors, ReneWerner87 and efectn and removed request for a team September 14, 2024 15:20
Copy link

welcome bot commented Sep 14, 2024

Thanks for opening this pull request! 🎉 Please check out our contributing guidelines. If you need help or want to chat with us, join us on Discord https://gofiber.io/discord

Copy link
Contributor

coderabbitai bot commented Sep 14, 2024

Walkthrough

The pull request introduces modifications to the registerStatic function in the fiber package to enhance path handling for static file serving, particularly when applications are mounted at specific paths. It also adds two new test functions in router_test.go to verify the functionality of static file routing, ensuring that both direct access and access through sub-applications to static files work correctly. Additionally, a new field parentApp is added to the mountFields struct in mount.go to improve path management.

Changes

Files Change Summary
router.go Modified registerStatic function to enhance path rewriting logic for static file serving.
router_test.go Added Test_Route_Static_HasPrefix and Test_Route_Static_SubApp to test static file routing functionality.
mount.go Introduced parentApp field in mountFields struct and added FullMountPath method to App struct for better path management.

Assessment against linked issues

Objective Addressed Explanation
Static server in sub app does not work (Issue #3104)

🐰 In the meadow where I hop and play,
A path was fixed to brighten the day.
Static files now serve with glee,
In sub-apps, they’re wild and free!
So come along, let’s cheer and sing,
For routing joy that changes bring! 🌼


Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 0bd4c0e and d415399.

Files selected for processing (3)
  • mount.go (3 hunks)
  • router.go (2 hunks)
  • router_test.go (2 hunks)
Files skipped from review as they are similar to previous changes (3)
  • mount.go
  • router.go
  • router_test.go

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 generate interesting stats about this repository and render them as a table.
    -- @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 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.

router_test.go Show resolved Hide resolved
@yinheli yinheli force-pushed the bugfix/static-server-in-sub-app branch 2 times, most recently from fe948ca to 506a800 Compare September 14, 2024 15:54
subApp := New()
subApp.Static("/css", dir)

app.Mount("/sub", subApp)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a testcase for nested mounting

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nested mounting is not working. I'll try to fix it.

@gaby gaby added v2 and removed v3 labels Sep 15, 2024
@gaby
Copy link
Member

gaby commented Sep 15, 2024

@yinheli Does this issue affect v3 too? If so, can you do a Pull Request against main for v3. Thanks!

@yinheli yinheli force-pushed the bugfix/static-server-in-sub-app branch 6 times, most recently from 733357b to 9808465 Compare September 15, 2024 16:01
router.go Outdated
@@ -357,6 +358,12 @@ func (app *App) registerStatic(prefix, root string, config ...Static) {
IndexNames: []string{"index.html"},
PathRewrite: func(fctx *fasthttp.RequestCtx) []byte {
path := fctx.Path()
mountPath := app.FullMountPath()
if n := len(mountPath); n > 0 {
if bytes.Equal(path[:n], utils.UnsafeBytes(mountPath)) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You don't need two-level if here. You can write:

if n := len(mountPath); n > 0 && bytes.Equal(path[:n], utils.UnsafeBytes(mountPath)) {
...
}

@@ -23,6 +23,8 @@ type mountFields struct {
subAppsProcessed sync.Once
// Prefix of app if it was mounted
mountPath string
// Parent app of the current app
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ReneWerner87 do you think we should use full-mount path for mounting? I think this might be a bug related to MountPath

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MountPath can only see that of subApp. Currently, the app cannot know how the upper layer is mounted. So I introduce a reference to Parent here. Do you have any good suggestions?

My current thinking is that when PathRewrite in registerStatic can replace the mounted part of the path.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@efectn @yinheli yes it should have something to do with the path
don't know if we necessarily need the complete parent reference for this

in the bug you said that the path is public/public, then we should start there

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@efectn @yinheli yes it should have something to do with the path don't know if we necessarily need the complete parent reference for this

in the bug you said that the path is public/public, then we should start there

Instead, perhaps we can do it during the path setting https://github.com/gofiber/fiber/blob/main/mount.go#L52

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have investigated this. However, here only the path of the subapp can be obtained. And registerStatic initializes the fileHandler when registering. So I chose the current implementation and added FullMountPath. I think that is easy to implement and has a lower cost.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have investigated this. However, here only the path of the subapp can be obtained. And registerStatic initializes the fileHandler when registering. So I chose the current implementation and added FullMountPath. I think that is easy to implement and has a lower cost.

Ok i will check it tomorrow

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Appreciate

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does the problem occur with v3 @yinheli ? I've just given a try with v3, and seems to work well:

func TestStaticMount(t *testing.T) {
	t.Parallel()
	app := fiber.New()
	sub := fiber.New()
	sub2 := fiber.New()

	sub2.Get("/doe*", New("../../.github"))

	sub.Use("/sub2", sub2)
	app.Use("/sub", sub)

	resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/sub/sub2/doe/release.yml", nil))
	require.NoError(t, err, "app.Test(req)")

	reqq, err := io.ReadAll(resp.Body)
	require.NoError(t, err)

	require.Equal(t, 200, resp.StatusCode, "Status code")
	require.Equal(t, uint32(1), app.HandlersCount())
	require.Equal(t, " ... ", string(reqq))
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I haven't investigated yet. I'm a bit busy during this period.

@yinheli yinheli force-pushed the bugfix/static-server-in-sub-app branch 3 times, most recently from 1ddc40f to 258e56e Compare September 15, 2024 16:09
@yinheli yinheli force-pushed the bugfix/static-server-in-sub-app branch from 258e56e to d415399 Compare September 15, 2024 16:20
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.

4 participants