Skip to content

🐛 bug: Add nil checks to End() to prevent panic in streaming mode#4128

Draft
Copilot wants to merge 3 commits intomainfrom
copilot/fix-context-end-functionality
Draft

🐛 bug: Add nil checks to End() to prevent panic in streaming mode#4128
Copilot wants to merge 3 commits intomainfrom
copilot/fix-context-end-functionality

Conversation

Copy link
Contributor

Copilot AI commented Mar 4, 2026

ctx.Conn() returns nil when fasthttp is operating in streaming mode (async connection management), and the fasthttp context itself (r.c.fasthttp) can also be nil after being returned to the pool. Calling methods on a nil context or bufio.NewWriter(nil) on a nil connection causes a nil pointer panic. End() now returns nil gracefully when either the context or connection is unavailable.

Changes introduced

  • res.go: Added nil guard on ctx (r.c.fasthttp) before calling ctx.Conn(), and a nil guard on conn before writing/flushing. Updated godoc to document the streaming limitation.
  • docs/api/ctx.md: Added :::warning admonition clarifying that End() is a no-op in streaming mode (HijackConn/SendStream) because ctx.Conn() may be nil.
// Before: panics if ctx == nil or ctx.Conn() == nil (streaming mode)
func (r *DefaultRes) End() error {
    ctx := r.c.fasthttp
    conn := ctx.Conn()          // panic if ctx is nil
    bw := bufio.NewWriter(conn) // panic if conn is nil
    ...
}

// After: safe nil checks for both ctx and conn
func (r *DefaultRes) End() error {
    ctx := r.c.fasthttp
    if ctx == nil {
        return nil
    }
    conn := ctx.Conn()
    if conn == nil {
        return nil
    }
    ...
}
  • Benchmarks: N/A — no hot-path change.
  • Documentation Update: docs/api/ctx.md updated with streaming caveat.
  • Changelog/What's New: Bug fix — End() no longer panics when ctx or connection is nil.
  • Migration Guide: No breaking changes.
  • API Alignment with Express: N/A.
  • API Longevity: Nil guards are additive; existing behavior unchanged for normal (non-streaming) requests.
  • Examples: See code snippet above.

Type of change

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

Checklist

  • 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.
Original prompt

This section details on the original issue you should resolve

<issue_title>🐛 [Bug]: does context.End even work?</issue_title>
<issue_description>### Bug Description

// End immediately flushes the current response and closes the underlying connection.
func (r *DefaultRes) End() error {
	ctx := r.c.fasthttp
	conn := ctx.Conn()

	bw := bufio.NewWriter(conn)
	if err := ctx.Response.Write(bw); err != nil {
		return err
	}

	if err := bw.Flush(); err != nil {
		return err //nolint:wrapcheck // unnecessary to wrap it
	}

	return conn.Close() //nolint:wrapcheck // unnecessary to wrap it
}

Does this code even work?

See

valyala/fasthttp#1309 (comment)

How to Reproduce

N/A

Expected Behavior

N/A

Fiber Version

N/A

Code Snippet (optional)

Checklist:

  • I agree to follow Fiber's Code of Conduct.
  • I have checked for existing issues that describe my problem prior to opening this one.
  • I understand that improperly formatted bug reports may be closed without explanation.</issue_description>

<agent_instructions>- Update the docs for End() based on comments above.

  • Add a nil check to End(), to make sure we do not panic while streaming.</agent_instructions>

Comments on the Issue (you are @copilot in this section)

@ReneWerner87 @grivera64 can you help here function was added in https://github.com//pull/3280 @ReneWerner87 can you share the error message/trace @gaby @pjebs We need more context and logs. When using streaming with fasthttp, it runs asynchronously, so if you call methods on our ctx, it's already put back on the pool by then. @gaby I think for now we should make sure this doesn't panic. We can address what to do with it later.

@pjebs So if ctx is nil here, we should just call return ?</comment_new>


💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.

Co-authored-by: gaby <835733+gaby@users.noreply.github.com>
Copilot AI changed the title [WIP] Fix issue with context.End functionality 🐛 bug: Add nil check to End() to prevent panic in streaming mode Mar 4, 2026
Copilot finished work on behalf of gaby March 4, 2026 02:17
@gaby
Copy link
Member

gaby commented Mar 4, 2026

@copilot check ctx before calling ctx.Conn(), that's where the panic could trigger.

Co-authored-by: gaby <835733+gaby@users.noreply.github.com>
Copy link
Contributor Author

Copilot AI commented Mar 4, 2026

@copilot check ctx before calling ctx.Conn(), that's where the panic could trigger.

Added a nil check for ctx before calling ctx.Conn() in commit ed3b0f5. The function now guards against both ctx == nil and conn == nil.

Copilot AI changed the title 🐛 bug: Add nil check to End() to prevent panic in streaming mode 🐛 bug: Add nil checks to End() to prevent panic in streaming mode Mar 4, 2026
Copilot finished work on behalf of gaby March 4, 2026 04:40
@ReneWerner87 ReneWerner87 added this to v3 Mar 4, 2026
@ReneWerner87 ReneWerner87 added this to the v3 milestone Mar 4, 2026
@codecov
Copy link

codecov bot commented Mar 4, 2026

Codecov Report

❌ Patch coverage is 0% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 91.04%. Comparing base (2262a42) to head (ed3b0f5).

Files with missing lines Patch % Lines
res.go 0.00% 2 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4128      +/-   ##
==========================================
- Coverage   91.07%   91.04%   -0.04%     
==========================================
  Files         119      119              
  Lines       11377    11381       +4     
==========================================
  Hits        10362    10362              
- Misses        645      647       +2     
- Partials      370      372       +2     
Flag Coverage Δ
unittests 91.04% <0.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.

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

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

🐛 [Bug]: does context.End even work?

3 participants