timeout

package module
v0.1.14 Latest Latest
Warning

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

Go to latest
Published: Jan 16, 2025 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package timeout provides middleware functionalities for setting timeout limits on processing HTTP requests in a web server. It allows developers to configure request timeouts to ensure that requests do not run indefinitely, improving server reliability.

Example
middleware := middleware.New()

middleware.Add(timeout.New().Settings(func(o *timeout.Options) { o.Timeout = time.Second * 30 }).Handler)

mux := http.NewServeMux()

mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	datum := map[string]interface{}{
		"timeout": timeout.Value(ctx).String(),
	}

	process := time.Duration(time.Second)

	select {
	case <-ctx.Done():
		return

	case t := <-time.After(process):
		// The (<-time.After(process)) channel simulates a long-running action.

		datum["time"] = t.String()
		datum["duration"] = process.String()

		// Because datum["time"] is non-deterministic, which will fail the output in example testing, we delete the key.

		delete(datum, "time")

		defer json.NewEncoder(w).Encode(datum)
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	return
})

server := httptest.NewServer(middleware.Handler(mux))

defer server.Close()

client := server.Client()
request, e := http.NewRequest(http.MethodGet, server.URL, nil)
if e != nil {
	e = fmt.Errorf("unexpected error while generating request: %w", e)

	panic(e)
}

response, e := client.Do(request)
if e != nil {
	e = fmt.Errorf("unexpected error while generating response: %w", e)

	panic(e)
}

defer response.Body.Close()

body, e := io.ReadAll(response.Body)
if e != nil {
	e = fmt.Errorf("unexpected error while reading response body: %w", e)

	panic(e)
}

fmt.Println(strings.TrimSpace(string(body)))
fmt.Printf("X-Timeout Header: %s", response.Header.Get("X-Timeout"))
Output:

{"duration":"1s","timeout":"30s"}
X-Timeout Header: 30s

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func New

func New() middleware.Configurable[Options]

New creates a new instance of the Timeout middleware, implementing middleware.Configurable. If Timeout.Settings isn't called, then the Timeout.Handler function will hydrate the middleware's configuration with sane default(s) if applicable.

func Value

func Value(ctx context.Context) (duration time.Duration)

Value retrieves a time.Duration from the provided context using a predefined key or returns a default timeout if the key's value is missing or invalid.

Types

type Options

type Options struct {
	// Timeout represents the duration to wait before considering an operation as timed out. If unspecified, or a negative value,
	// a default of 30 seconds is overwritten.
	Timeout time.Duration

	// Header represents an optional response-header key. Setting the [Options.Header] to an empty string will prevent
	// the response from including the Header key-value. By default, the Header is set to "X-Timeout".
	Header string
}

Options defines configurable settings for timeout behaviors, including response header customization and operation timeout durations.

type Timeout

type Timeout struct {
	middleware.Configurable[Options]
	// contains filtered or unexported fields
}

Timeout represents a middleware component that applies configurable timeout settings to HTTP requests. It embeds middleware.Configurable for Options configuration.

func (*Timeout) Handler

func (t *Timeout) Handler(next http.Handler) http.Handler

Handler applies timeout middleware to the provided HTTP handler, enforcing a request timeout and adding optional timeout metadata to the response.

func (*Timeout) Settings

func (t *Timeout) Settings(configuration ...func(o *Options)) middleware.Configurable[Options]

Settings applies configuration functions to modify the Timeout middleware's Options and returns the updated middleware instance.

Jump to

Keyboard shortcuts

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