Thanks to visit codestin.com
Credit goes to github.com

Skip to content

🐛 bug: harden Port() handling#4051

Merged
ReneWerner87 merged 2 commits intomainfrom
update-defaultreq.port-to-prevent-panic
Feb 4, 2026
Merged

🐛 bug: harden Port() handling#4051
ReneWerner87 merged 2 commits intomainfrom
update-defaultreq.port-to-prevent-panic

Conversation

@gaby
Copy link
Member

@gaby gaby commented Feb 4, 2026

Motivation

  • DefaultReq.Port() previously type-asserted the fasthttp remote address to *net.TCPAddr and could panic for non-TCP addresses or other address shapes, so it must be made robust with sensible fallbacks.
  • Improve safety for unix sockets and string-style remote addresses while preserving TCP port extraction.
  • Add unit tests to fully exercise all code paths and reach 100% coverage for the function.

Description

  • Replace the fragile type assertion in DefaultReq.Port() with a type switch that handles *net.TCPAddr (return port), *net.UnixAddr (return empty string), and falls back to net.SplitHostPort(addr.String()) for other net.Addr implementations; return empty string when a port cannot be determined.
  • Remove the now-unused errTCPAddrTypeAssertion constant from errors_internal.go.
  • Add table-driven unit tests in ctx_test.go (new Test_Ctx_Port_RemoteAddrVariants) that exercise TCP, Unix socket, default remote (nil), host:port string, missing-port string, and IPv6 bracketed addresses; include a small testNetAddr implementation to simulate string-style net.Addr values and set the remote address via DefaultCtx.fasthttp.SetRemoteAddr.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @gaby, 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 enhances the reliability and safety of the DefaultReq.Port() function by making it resilient to diverse network address types. The changes prevent potential panics by gracefully handling non-TCP addresses and ensure correct port extraction or appropriate fallback behavior for various remote address formats. This also includes a substantial increase in test coverage to validate the new logic.

Highlights

  • Robust Port Extraction: The DefaultReq.Port() function has been refactored to handle various net.Addr implementations more robustly, preventing panics that could occur with non-TCP addresses.
  • Type Switch Implementation: The function now uses a type switch to specifically handle *net.TCPAddr (extracting the port), *net.UnixAddr (returning an empty string), and falls back to net.SplitHostPort for other net.Addr types.
  • Error Constant Removal: The errTCPAddrTypeAssertion constant has been removed from errors_internal.go as it is no longer needed due to the improved port extraction logic.
  • Enhanced Test Coverage: A new table-driven unit test, Test_Ctx_Port_RemoteAddrVariants, has been added to ctx_test.go to ensure 100% coverage for the Port() function across various remote address scenarios, including TCP, Unix sockets, nil addresses, string-based host:port, and IPv6 addresses.
  • Test Utility: A testNetAddr struct was introduced in ctx_test.go to facilitate testing with custom string-style net.Addr values.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • ctx_test.go
    • Added testNetAddr struct to simulate net.Addr for testing purposes.
    • Introduced Test_Ctx_Port_RemoteAddrVariants to thoroughly test Port() with different remote address types (TCP, Unix, nil, string-based host:port, IPv6).
  • errors_internal.go
    • Removed the errTCPAddrTypeAssertion constant, which is no longer relevant after the Port() function refactor.
  • req.go
    • Modified DefaultReq.Port() to use a type switch for *net.TCPAddr and *net.UnixAddr.
    • Implemented a fallback mechanism using net.SplitHostPort for other net.Addr types, ensuring robust port extraction.
    • Removed the panic on type assertion failure, replacing it with safer handling.
Activity
  • make audit failed due to govulncheck reporting Go standard library vulnerabilities.
  • make generate, make betteralign, make modernize, and make format all succeeded.
  • make lint succeeded with 0 issues reported.
  • make test succeeded, completing 2618 tests.
  • The newly added unit test Test_Ctx_Port_RemoteAddrVariants was run directly and passed.
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 by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

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 pull request 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 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. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

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.

@ReneWerner87 ReneWerner87 added this to v3 Feb 4, 2026
@ReneWerner87 ReneWerner87 added this to the v3 milestone Feb 4, 2026
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 4, 2026

Walkthrough

Port() was made more robust: it now safely handles various net.Addr implementations (nil, *net.TCPAddr, *net.UnixAddr, and other String()-based addresses) via a type switch and fallback parsing. Tests were added to verify port extraction across multiple remote address variants, including IPv6 and missing ports.

Changes

Cohort / File(s) Summary
Implementation & Error Cleanup
req.go, errors_internal.go
Rewrote Port() to use a type switch and safe fallbacks instead of a strict type assertion that could panic. Removed the now-unused errTCPAddrTypeAssertion error variable.
Test Coverage
ctx_test.go
Added Test_Ctx_Port_RemoteAddrVariants and a testNetAddr test type to validate Port() behavior for nil, *net.TCPAddr, *net.UnixAddr, and custom address string formats (including IPv6 and absent ports).

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Suggested reviewers

  • sixcolors
  • ReneWerner87
  • efectn

Poem

🐰 I hopped through nets with gentle art,
Ports parsed clean from every part;
No sudden panic, calm and bright,
TCP, Unix, IPv6 — all right! 🎉

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly references the main change: hardening the Port() method to handle multiple address types safely without panicking.
Description check ✅ Passed The PR description covers motivation, implementation details, and testing approach comprehensively, though it deviates from the repository's formal template structure.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch update-defaultreq.port-to-prevent-panic

Important

Action Needed: IP Allowlist Update

If your organization protects your Git platform with IP whitelisting, please add the new CodeRabbit IP address to your allowlist:

  • 136.113.208.247/32 (new)
  • 34.170.211.100/32
  • 35.222.179.152/32

Reviews will stop working after February 8, 2026 if the new IP is not added to your allowlist.


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

Comment @coderabbitai help to get the list of available commands and usage tips.

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 effectively hardens the Port() function by replacing a direct type assertion with a more robust type switch, correctly handling various net.Addr implementations like *net.TCPAddr and *net.UnixAddr, and providing a sensible fallback for other address types. The addition of comprehensive, table-driven unit tests is excellent, ensuring all new code paths are covered and preventing future regressions. The removal of the now-unused errTCPAddrTypeAssertion is a nice cleanup. I have one minor suggestion to further improve the robustness of the Port() function.

@codecov
Copy link

codecov bot commented Feb 4, 2026

Codecov Report

❌ Patch coverage is 83.33333% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 91.16%. Comparing base (eec1258) to head (7e601e8).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
req.go 83.33% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4051      +/-   ##
==========================================
- Coverage   91.21%   91.16%   -0.05%     
==========================================
  Files         119      119              
  Lines       11121    11129       +8     
==========================================
+ Hits        10144    10146       +2     
- Misses        620      625       +5     
- Partials      357      358       +1     
Flag Coverage Δ
unittests 91.16% <83.33%> (-0.05%) ⬇️

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.

@gaby gaby changed the title 🐛 bug: harden Port() handling and add coverage 🐛 bug: harden Port() handling Feb 4, 2026
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR refactors the DefaultReq.Port() method to replace a fragile type assertion with a type switch that safely handles different net.Addr implementations, and adds comprehensive unit tests to cover all code paths.

Changes:

  • Replaced panic-prone type assertion in Port() with a type switch handling TCP, Unix, and other address types
  • Removed unused errTCPAddrTypeAssertion error constant
  • Added comprehensive test coverage with new Test_Ctx_Port_RemoteAddrVariants test and testNetAddr helper

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

File Description
req.go Refactored Port() method to use type switch for safe handling of different address types
errors_internal.go Removed unused errTCPAddrTypeAssertion constant
ctx_test.go Added comprehensive test coverage with testNetAddr helper and Test_Ctx_Port_RemoteAddrVariants test

@ReneWerner87 ReneWerner87 merged commit 8d8877f into main Feb 4, 2026
16 of 17 checks passed
@ReneWerner87 ReneWerner87 deleted the update-defaultreq.port-to-prevent-panic branch February 4, 2026 16:02
@github-project-automation github-project-automation bot moved this to Done in v3 Feb 4, 2026
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.

3 participants