Skip to content

🔥 feat: Add UNIX socket support#3535

Merged
ReneWerner87 merged 13 commits intogofiber:mainfrom
LaptopCat:main
Jun 30, 2025
Merged

🔥 feat: Add UNIX socket support#3535
ReneWerner87 merged 13 commits intogofiber:mainfrom
LaptopCat:main

Conversation

@LaptopCat
Copy link
Contributor

Description

This pull request improves support for listening on unix domain sockets:

  1. Remove the old unix socket before listening
  2. Change unix socket permissions after listening, to new option UnixSocketFileMode which is specified in ListenConfig

Inspired by ListenAndServeUNIX function from fasthttp

Changes introduced

  • Documentation Update: Updated ListenConfig docs (added UnixSocketFileMode and update ListenerNetwork description)

Type of change

  • Enhancement (improvement to existing features and functionality)
  • Documentation update (changes to documentation)

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.

Commit formatting

Please use emojis in commit messages for an easy way to identify the purpose or intention of a commit. Check out the emoji cheatsheet here: CONTRIBUTING.md

@LaptopCat LaptopCat requested a review from a team as a code owner June 22, 2025 10:56
@welcome
Copy link

welcome bot commented Jun 22, 2025

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

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 22, 2025

"""

Walkthrough

Support for Unix Domain Sockets was added to the ListenConfig struct in the Fiber package. This includes a new UnixSocketFileMode field for setting socket file permissions and updates to documentation and listener creation logic to handle Unix sockets, including file cleanup and permission setting.

Changes

File(s) Change Summary
docs/api/fiber.md Updated documentation for ListenConfig to include Unix Domain Socket support and new field.
listen.go Added UnixSocketFileMode to ListenConfig, updated listener creation for Unix sockets.
constants.go Added new constant NetworkUnix = "unix" for Unix Domain Socket network type.
listen_test.go Added test coverage for listening on Unix Domain Socket with permission and cleanup verification.
docs/whats_new.md Added documentation describing Unix socket support in Fiber v3 with usage examples.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant FiberApp
    participant ListenConfig
    participant OS

    User->>FiberApp: Start app with ListenConfig (ListenerNetwork="unix")
    FiberApp->>ListenConfig: Read UnixSocketFileMode
    FiberApp->>OS: Remove existing socket file (if any)
    OS-->>FiberApp: Success or "file not exist"
    FiberApp->>OS: Create Unix Domain Socket listener
    FiberApp->>OS: Set socket file permissions (UnixSocketFileMode)
    OS-->>FiberApp: Permissions set
    FiberApp-->>User: App ready and listening on Unix socket
Loading

Suggested reviewers

  • gaby
  • ReneWerner87

Poem

🐇
A socket on Unix, so neat and so new,
With permissions to set—oh what will you do?
No more stray files left behind in the night,
The listener cleans up, and sets things just right.
Fiber hops forward, with sockets in view!
🐾✨
"""


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 82ae09f and f5310e5.

📒 Files selected for processing (1)
  • docs/whats_new.md (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • docs/whats_new.md
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: Analyse
  • GitHub Check: lint
  • GitHub Check: Compare
  • 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: repeated
  • GitHub Check: unit (1.24.x, ubuntu-latest)

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.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Summary of Changes

Hello @LaptopCat, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly improves the robustness and configurability of Unix domain socket support within the application. It addresses common issues related to socket file persistence and provides greater control over file permissions, making the Unix socket listening process more reliable and user-friendly.

Highlights

  • Enhanced Unix Socket Management: Implemented automatic removal of existing Unix domain socket files before attempting to listen on them, preventing 'address already in use' errors on restart.
  • Configurable Unix Socket Permissions: Introduced a new UnixSocketFileMode option in ListenConfig to allow users to specify the file permissions for Unix domain sockets. The default permission is 0775.
  • Documentation Updates: Updated the ListenConfig documentation to include the new UnixSocketFileMode field and clarified the ListenerNetwork description to explicitly mention 'unix' as a supported network type.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a 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 enhances Unix domain socket support by cleaning up old sockets and allowing file mode configuration. The review focuses on improving the security of the default file mode and enhancing code maintainability by using constants for network types.

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

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

291-314: Consider defining a constant for the "unix" network type.

While the implementation is correct, using a string literal "unix" in multiple places could benefit from a defined constant to avoid potential typos and improve maintainability.

Consider adding this constant alongside the existing network constants:

const (
	globalIpv4Addr = "0.0.0.0"
+	NetworkUnix    = "unix"
)

Then use it in the conditional checks:

-if cfg.ListenerNetwork == "unix" {
+if cfg.ListenerNetwork == NetworkUnix {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e1a7c11 and 7eec20b.

📒 Files selected for processing (2)
  • docs/api/fiber.md (1 hunks)
  • listen.go (5 hunks)
🔇 Additional comments (5)
docs/api/fiber.md (1)

116-117: Documentation accurately reflects the new Unix socket support.

The documentation updates correctly describe the new Unix Domain Socket functionality. The ListenerNetwork field now properly lists "unix" as a valid option, and the new UnixSocketFileMode field is well-documented with its type and default value.

listen.go (4)

75-78: Well-documented Unix socket file mode configuration.

The new UnixSocketFileMode field is properly documented and follows Go struct field conventions. The default value of 0775 provides reasonable permissions while remaining configurable for security-conscious deployments.


131-135: Proper default value handling for Unix socket file mode.

The default configuration logic correctly initializes UnixSocketFileMode to 0o775. The octal notation is clear and the conditional check ensures the default is applied when the field is zero-valued.

Also applies to: 143-145


291-296: Robust Unix socket file cleanup implementation.

The pre-listen socket file removal correctly handles the common case where a previous socket file exists. The error handling properly ignores "file not exist" errors while propagating other unexpected errors. This prevents "address already in use" errors on server restart.


310-314: Correct file permission setting for Unix sockets.

The implementation properly sets Unix socket file permissions after successful socket creation using os.Chmod. The error handling provides descriptive messages with the attempted permissions and file path for debugging.

@gaby gaby changed the title 🧹 chore: Improve unix socket support 🔥 feat: Add Unix socket support Jun 22, 2025
@gaby gaby added this to v3 Jun 22, 2025
@gaby gaby added this to the v3 milestone Jun 22, 2025
@gaby
Copy link
Member

gaby commented Jun 22, 2025

@LaptopCat Please add unit+tests for this functionality

@codecov
Copy link

codecov bot commented Jun 22, 2025

Codecov Report

Attention: Patch coverage is 62.50000% with 6 lines in your changes missing coverage. Please review.

Project coverage is 91.00%. Comparing base (55818fb) to head (f5310e5).
Report is 6 commits behind head on main.

Files with missing lines Patch % Lines
listen.go 62.50% 4 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3535      +/-   ##
==========================================
- Coverage   91.02%   91.00%   -0.03%     
==========================================
  Files         110      110              
  Lines       10955    10989      +34     
==========================================
+ Hits         9972    10000      +28     
- Misses        731      735       +4     
- Partials      252      254       +2     
Flag Coverage Δ
unittests 91.00% <62.50%> (-0.03%) ⬇️

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.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b9830bf and 0e497cd.

📒 Files selected for processing (1)
  • listen_test.go (2 hunks)
🔇 Additional comments (1)
listen_test.go (1)

13-13: LGTM!

The import of path/filepath is appropriate for the filepath.Join function used in the Unix socket test case.

@gaby gaby moved this to In Progress in v3 Jun 22, 2025
@gaby
Copy link
Member

gaby commented Jun 22, 2025

@LaptopCat Can you mark the fixes you have applied as "Resolved". Thanks! 💪

@ReneWerner87
Copy link
Member

@LaptopCat can you extend the markdown ?

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

🧹 Nitpick comments (2)
docs/whats_new.md (2)

238-238: Suggest more descriptive bullet for Unix socket support.

Consider referencing the new config fields to help readers quickly locate the feature (e.g., ListenerNetwork and UnixSocketFileMode).

For example:

- - Added Unix socket support
+ - Added support for Unix domain sockets via `ListenerNetwork` and `UnixSocketFileMode`

241-258: Add error handling to cleanup and listen calls.

The examples omit error checks on os.Remove, os.Chmod, and app.Listen. Handling or explicitly ignoring errors prevents silent failures. For example:

- os.Remove("app.sock")
+ _ = os.Remove("app.sock") // ignore if not exists

- app.Hooks().OnListen(func(fiber.ListenData) error {
-     return os.Chmod("app.sock", 0777)
- })
+ app.Hooks().OnListen(func(_ fiber.ListenData) error {
+     return os.Chmod("app.sock", 0777)
+ })

- app.Listen("app.sock")
+ if err := app.Listen("app.sock"); err != nil {
+     log.Fatalf("failed to listen on unix socket: %v", err)
+ }

And for v3:

- app.Listen("app.sock", fiber.ListenerConfig{
-     ListenerNetwork:    fiber.NetworkUnix,
-     UnixSocketFileMode: 0777,
- })
+ if err := app.Listen("app.sock", fiber.ListenerConfig{
+     ListenerNetwork:    fiber.NetworkUnix,
+     UnixSocketFileMode: 0777,
+ }); err != nil {
+     log.Fatalf("failed to listen on unix socket: %v", err)
+ }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 36c9da9 and 7f31599.

📒 Files selected for processing (1)
  • docs/whats_new.md (1 hunks)

@gaby gaby changed the title 🔥 feat: Add Unix socket support 🔥 feat: Add UNIX socket support Jun 24, 2025
Copy link
Member

@gaby gaby left a comment

Choose a reason for hiding this comment

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

Few conments

@ReneWerner87
Copy link
Member

@LaptopCat can you recheck the hints and then we can merge

Copy link
Member

@gaby gaby left a comment

Choose a reason for hiding this comment

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

LGTM

@gaby gaby requested a review from ReneWerner87 June 28, 2025 18:37
@ReneWerner87 ReneWerner87 merged commit cfa5b3a into gofiber:main Jun 30, 2025
13 of 14 checks passed
@welcome
Copy link

welcome bot commented Jun 30, 2025

Congrats on merging your first pull request! 🎉 We here at Fiber are proud of you! If you need help or want to chat with us, join us on Discord https://gofiber.io/discord

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

4 participants