Skip to content

🐛 [Bug]: FiberHandler adaptor does not flush when using SendStreamWriter #3798

@grivera64

Description

@grivera64

Bug Description

In the opposite direction of #3421, there is also a bug where adaptor.FiberHandler also does not support buffered streaming directly to a net/http handler.

How to Reproduce

Steps to reproduce the behavior:

  1. Create a fiber handler that uses c.SendStreamWriter()
  2. Use adaptor.FiberHandler() to convert to a http.Handler.
  3. Call handler.ServerHTTP(w, r) within a net/http` handler func.
  4. Run the binary and run curl localhost:3000/stream.

Expected Behavior

The expected behavior is to have the BodyStream run, if present. The data should come sent as a buffered stream as w is written to.

Fiber Version

v3.0.0-rc.2

Code Snippet (optional)

package main

import (
	"bufio"
	"fmt"
	"io"

	"time"

	"github.com/gofiber/fiber/v3"
	"github.com/gofiber/fiber/v3/middleware/adaptor"
	"net/http"
)

func main() {
	handler := adaptor.FiberHandler(func(c fiber.Ctx) error {
		c.Set("Content-Type", "text/plain; charset=utf-8")
		c.Set("Cache-Control", "no-cache")
		c.Set("Connection", "keep-alive")
		c.Set("Transfer-Encoding", "chunked")
		return c.SendStreamWriter(func(w *bufio.Writer) {
			for i := 1; i <= 10; i++ {
				msg := fmt.Sprintf("Line %d\n", i)
				_, err := w.WriteString(msg)
				if err != nil {
					if err == io.ErrClosedPipe {
						return
					}
					fmt.Println("net/http: write error:", err)
					return
				}
				err = w.Flush()
				if err != nil {
					if err == io.ErrClosedPipe {
						return
					}
					fmt.Println("net/http: flush error:", err)
					return
				}
				if i < 10 {
					time.Sleep(1 * time.Second)
				}
			}
		})
	})
	http.HandleFunc("/stream", func(w http.ResponseWriter, r *http.Request) {
		handler.ServeHTTP(w, r)
	})
	http.ListenAndServe(":3000", nil)
}

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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions