fiberclose

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 6, 2026 License: MIT Imports: 5 Imported by: 0

README

Fiber Close

Simple package that fixes the known Fiber / FastHTTP issue with context closure on connection closure.

TL;DR FastHTTP doesn't close context when connection is closed.

More on this issue here: https://github.com/valyala/fasthttp/issues/965#issuecomment-777268945

Usage

Install fiberclose.

go get -u github.com/mymmrac/fiberclose

Use it for the Fiber app.

  1. Use middleware:
app.Use(fiberclose.Middleware())
  1. Always use fiber.Ctx.Context():
ctx := fCtx.Context()
  1. Use listener wrapper:
app.Listener(fiberclose.Listener(ln))

Full example:

package main

import (
	"fmt"
	"net"

	"github.com/gofiber/fiber/v3"

	"github.com/mymmrac/fiberclose"
)

func main() {
	app := fiber.New()
	// Use fiberclose middleware
	app.Use(fiberclose.Middleware())

	app.Get("/", func(fCtx fiber.Ctx) error {
		// Always use user context
		ctx := fCtx.Context()
		fmt.Println("Connection open")

		<-ctx.Done()

		fmt.Println("Connection closed")
		return nil
	})

	ln, err := net.Listen("tcp", ":8080")
	if err != nil {
		// ...
	}

	// Use fiberclose listener wrapper
	if err = app.Listener(fiberclose.Listener(ln)); err != nil {
		// ...
	}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Listener

func Listener(ln net.Listener) net.Listener

Listener wraps net.Listener to support closing Fiber context on connection close.

func Middleware

func Middleware(opts ...Option) fiber.Handler

Middleware changes the default behavior of Fiber/FastHTTP context. Once the connection is closed, context will also be closed (in default Fiber/FastHTTP context is closed only on server shutdown).

Note: Only fiber.Ctx.Context will be properly closed.

Types

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option options.

func WithUserContext

func WithUserContext() Option

WithUserContext keeps user context as base context. Default uses FastHTTP's context.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL