foxtimeout

package module
v0.26.2 Latest Latest
Warning

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

Go to latest
Published: Jan 31, 2026 License: MIT Imports: 14 Imported by: 0

README

Go Reference tests Go Report Card codecov GitHub release (latest SemVer) GitHub go.mod Go version

Foxtimeout

Foxtimeout is a middleware for Fox which ensure that a handler do not exceed the configured timeout limit.

Disclaimer

Foxtimeout's API is closely tied to the Fox router, and it will only reach v1 when the router is stabilized. During the pre-v1 phase, breaking changes may occur and will be documented in the release notes.

Getting started

Installation
go get -u github.com/tigerwill90/foxtimeout
Feature
  • Allows for custom timeout response to better suit specific use cases.
  • Tightly integrates with the Fox ecosystem for enhanced performance and scalability.
  • Supports dynamic timeout configuration on a per-route & per-request basis using custom Resolver.
Usage
package main

import (
	"errors"
	"fmt"
	"log"
	"net/http"
	"time"

	"github.com/tigerwill90/fox"
	"github.com/tigerwill90/foxtimeout"
)

func main() {
	f := fox.MustRouter(
		fox.DefaultOptions(),
		fox.WithMiddleware(
			foxtimeout.Middleware(2*time.Second),
		),
	)

	f.MustAdd(fox.MethodGet, "/hello/{name}", func(c *fox.Context) {
		_ = c.String(http.StatusOK, fmt.Sprintf("Hello %s\n", c.Param("name")))
	})
	// Disable timeout the middleware for this route
	f.MustAdd(fox.MethodGet, "/download/{filepath}", DownloadHandler, foxtimeout.HandlerTimeout(foxtimeout.NoTimeout))
	// Use 15s timeout instead of the global 2s for this route
	f.MustAdd(fox.MethodGet, "/workflow/{id}/start", WorkflowHandler, foxtimeout.HandlerTimeout(15*time.Second))

	if err := http.ListenAndServe(":8080", f); err != nil && !errors.Is(err, http.ErrServerClosed) {
		log.Fatalln(err)
	}
}

Documentation

Index

Examples

Constants

View Source
const NoTimeout = time.Duration(0)

Variables

This section is empty.

Functions

func DefaultTimeoutResponse

func DefaultTimeoutResponse(c *fox.Context)

DefaultTimeoutResponse sends a default 503 Service Unavailable response.

func HandlerTimeout added in v0.26.0

func HandlerTimeout(dt time.Duration) fox.RouteOption

HandlerTimeout returns a RouteOption that sets a custom timeout duration for a specific route. This allows individual routes to have different timeout values than the global timeout. Passing a value <= 0 (or NoTimeout) disables the timeout for this route.

Example
f, err := fox.NewRouter(
	fox.WithMiddleware(Middleware(2 * time.Second)),
)
if err != nil {
	panic(err)
}

f.MustAdd(fox.MethodGet, "/hello/{name}", func(c *fox.Context) {
	_ = c.String(http.StatusOK, fmt.Sprintf("hello %s\n", c.Param("name")))
})

f.MustAdd(fox.MethodGet, "/long", func(c *fox.Context) {
	time.Sleep(10 * time.Second)
	c.Writer().WriteHeader(http.StatusOK)
}, HandlerTimeout(12*time.Second))

f.MustAdd(fox.MethodGet, "/no-timeout", func(c *fox.Context) {
	c.Writer().WriteHeader(http.StatusOK)
}, HandlerTimeout(NoTimeout))

func Middleware

func Middleware(dt time.Duration, opts ...Option) fox.MiddlewareFunc

Middleware returns a fox.MiddlewareFunc that runs handlers with the given time limit.

The middleware calls the next handler to handle each request, but if a call runs for longer than its time limit, the handler responds with a 503 Service Unavailable error and the given message in its body (if a custom response handler is not configured). After such a timeout, writes by the handler to its ResponseWriter will return http.ErrHandlerTimeout.

The timeout middleware supports the http.Pusher interface but does not support the http.Hijacker or http.Flusher interfaces.

Individual routes can override the timeout duration using the HandlerTimeout option. It's also possible to set the read and write deadline for individual route using the ReadTimeout and WriteTimeout option. If dt <= 0 (or NoTimeout), this is a passthrough middleware but per-route options remain effective.

func ReadTimeout added in v0.26.0

func ReadTimeout(dt time.Duration) fox.RouteOption

ReadTimeout returns a RouteOption that sets the read deadline for the underlying connection. This controls how long the server will wait for the client to send request data. A zero duration is not allowed and will return an error during route registration.

func WriteTimeout added in v0.26.0

func WriteTimeout(dt time.Duration) fox.RouteOption

WriteTimeout returns a RouteOption that sets the write deadline for the underlying connection. This controls how long the server will wait before timing out writes to the client. A zero duration is not allowed and will return an error during route registration.

Types

type Filter

type Filter func(c *fox.Context) (skip bool)

type Option

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

func WithFilter

func WithFilter(f ...Filter) Option

WithFilter appends the provided filters to the middleware's filter list. A filter returning true will exclude the request from using the timeout handler. If no filters are provided, all requests will be handled. Keep in mind that filters are invoked for each request, so they should be simple and efficient.

func WithResponse

func WithResponse(h fox.HandlerFunc) Option

WithResponse sets a custom response handler function for the middleware. This function will be invoked when a timeout occurs, allowing for custom responses to be sent back to the client. If not set, the middleware use DefaultTimeoutResponse.

type Timeout

type Timeout struct {
	// contains filtered or unexported fields
}

Timeout is a middleware that ensure HTTP handlers don't exceed the configured timeout duration.

Jump to

Keyboard shortcuts

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