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

Skip to content

🐛 bug: harden DefaultRes.Format against nil handler panics#4105

Merged
ReneWerner87 merged 1 commit intomainfrom
harden-defaultres.format-against-nil-handlers
Feb 24, 2026
Merged

🐛 bug: harden DefaultRes.Format against nil handler panics#4105
ReneWerner87 merged 1 commit intomainfrom
harden-defaultres.format-against-nil-handlers

Conversation

@gaby
Copy link
Member

@gaby gaby commented Feb 23, 2026

Motivation

  • Prevent runtime panics when user-provided ResFmt.Handler entries are nil by validating handlers before running content negotiation and make debugging easier by returning a descriptive error that includes the media type and handler index.

Description

  • Added an upfront validation loop in DefaultRes.Format that returns fmt.Errorf("format handler is nil for media type %q at index %d", ...) when any ResFmt.Handler is nil, performed before Vary/Accept negotiation so existing flow is preserved (matching, default fallback, 406 behavior).
  • Kept the existing content-negotiation behavior unchanged once validation passes, including the existing default handler and StatusNotAcceptable fallback.
  • Added Test_Ctx_Format_NilHandler in ctx_test.go with three subtests that assert (and use require.NotPanics) for: nil handler in the first entry, nil handler in the matched media type, and nil default handler.

Copilot AI review requested due to automatic review settings February 23, 2026 13:47
@gaby gaby requested a review from a team as a code owner February 23, 2026 13:47
@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 enhances the robustness of the DefaultRes.Format method by introducing a validation step that checks for nil format handlers before content negotiation. This change prevents potential runtime panics and provides more informative error messages, improving the overall stability and debuggability of the application's response formatting logic.

Highlights

  • Panic Prevention: Implemented upfront validation in DefaultRes.Format to prevent runtime panics when user-provided ResFmt.Handler entries are nil.
  • Improved Error Handling: Returns a descriptive error message including the media type and handler index when a nil handler is encountered, making debugging easier.
  • New Test Cases: Added Test_Ctx_Format_NilHandler with subtests to assert correct error handling and non-panicking behavior for various nil handler scenarios.
Changelog
  • ctx_test.go
    • Added Test_Ctx_Format_NilHandler to verify that c.Format correctly handles nil handlers without panicking and returns appropriate errors.
  • res.go
    • Introduced a loop in DefaultRes.Format to check for nil ResFmt.Handler entries, returning a detailed error if found.
Activity
  • Ran go test ./... -run 'Test_Ctx_Format|Test_Ctx_Format_NilHandler', confirming targeted tests passed and nil-handler tests asserted errors without panicking.
  • Executed make test, make generate, make modernize, make format, make lint, and make betteralign, all completing successfully.
  • Ran make audit, which reported existing Go standard-library vulnerabilities, noted as an environment/toolchain issue unrelated to these changes.
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.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 23, 2026

Walkthrough

Adds nil Handler validation in DefaultRes.Format to prevent runtime errors, returning a formatted error message when a nil handler is encountered. Corresponding test coverage validates nil handler behavior across first entry, matched media types, and default handler scenarios.

Changes

Cohort / File(s) Summary
Nil Handler Validation
res.go
Adds pre-validation loop in DefaultRes.Format that checks each ResFmt for non-nil Handler, returning formatted error with media type and index if nil handler found.
Test Coverage
ctx_test.go
Introduces 60 lines of test cases covering nil handler scenarios: nil handler in first entry, matched media type, and default handler cases.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

☢️ Bug, v3

Suggested reviewers

  • sixcolors
  • efectn
  • ReneWerner87

Poem

A rabbit checks handlers with care so keen, 🐰
No nil shall slip through, keen-eyed and seen,
With tests standing guard at each index's door,
The format flows safe forevermore! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: hardening DefaultRes.Format against nil handler panics, which matches the core functionality added in res.go.
Description check ✅ Passed The PR description provides clear motivation, technical details of changes, and comprehensive testing results, addressing the core requirements effectively.

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

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch harden-defaultres.format-against-nil-handlers

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

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 hardens the DefaultRes.Format method against runtime panics by adding upfront validation for nil handlers in the ResFmt slice. When a user provides a nil handler, the method now returns a descriptive error instead of panicking during content negotiation or handler execution.

Changes:

  • Added validation loop in DefaultRes.Format to check for nil handlers before content negotiation
  • Added comprehensive test coverage with three subtests covering different nil handler scenarios

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
res.go Added upfront nil handler validation loop that returns descriptive errors with media type and index information
ctx_test.go Added Test_Ctx_Format_NilHandler with three subtests verifying nil handlers don't panic and return proper errors

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

The pull request successfully addresses the potential runtime panics in DefaultRes.Format by adding an upfront validation loop for nil handlers. The implementation is clean, efficient, and includes comprehensive tests covering various edge cases. The defensive check ensures that the API contract is respected and provides helpful debugging information through descriptive error messages.

@codecov
Copy link

codecov bot commented Feb 23, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.00%. Comparing base (af52730) to head (69324b9).
⚠️ Report is 27 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4105      +/-   ##
==========================================
- Coverage   91.03%   91.00%   -0.04%     
==========================================
  Files         119      119              
  Lines       11324    11340      +16     
==========================================
+ Hits        10309    10320      +11     
- Misses        643      648       +5     
  Partials      372      372              
Flag Coverage Δ
unittests 91.00% <100.00%> (-0.04%) ⬇️

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

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

⚠️ Performance Alert ⚠️

Possible performance regression was detected for benchmark.
Benchmark result of this commit is worse than the previous benchmark result exceeding threshold 1.50.

Benchmark suite Current: 69324b9 Previous: 92ada8a Ratio
BenchmarkDecoderedirectionMsgs - MB/s 114.83 MB/s 47.86 MB/s 2.40

This comment was automatically generated by workflow using github-action-benchmark.

@ReneWerner87 ReneWerner87 merged commit 082e205 into main Feb 24, 2026
34 of 43 checks passed
@ReneWerner87 ReneWerner87 deleted the harden-defaultres.format-against-nil-handlers branch February 24, 2026 07:33
@github-project-automation github-project-automation bot moved this to Done in v3 Feb 24, 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