Skip to content

tigerwill90/foxtimeout

Repository files navigation

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 (
	"github.com/tigerwill90/fox"
	"github.com/tigerwill90/foxtimeout"
	"log"
	"net/http"
	"time"
)

func main() {
	resolver := foxtimeout.TimeoutResolverFunc(func(c fox.Context) (dt time.Duration, ok bool) {
		for annotation := range c.Route().Annotations() {
			if annotation.Key == "timeout" {
				dt, ok = annotation.Value.(time.Duration)
				return dt, ok
			}
		}
		return 0, false
	})

	f := fox.New(
		fox.DefaultOptions(),
		fox.WithMiddlewareFor(
			fox.RouteHandler,
			foxtimeout.Middleware(
				2*time.Second,
				foxtimeout.WithTimeoutResolver(resolver),
			),
		),
	)

	f.MustHandle(http.MethodGet, "/hello/{name}", func(c fox.Context) {
		_ = c.String(http.StatusOK, "hello %s\n", c.Param("name"))
	})
	f.MustHandle(http.MethodGet, "/long_job", func(c fox.Context) {
		time.Sleep(10 * time.Second)
		c.Writer().WriteHeader(http.StatusOK)
	}, fox.WithAnnotation("timeout", 15*time.Second))

	log.Fatalln(http.ListenAndServe(":8080", f))
}