httpsrv

package
v1.26.0 Latest Latest
Warning

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

Go to latest
Published: Jun 12, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package httpsrv provides net/http middleware that subjects inbound requests to chaos. The Middleware mounts in any net/http chain.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Middleware

func Middleware(eng *engine.Engine) func(http.Handler) http.Handler

Middleware returns an http middleware that consults eng on every request. If eng is nil or has no rules, the wrapper is a near-zero-cost passthrough.

Example
package main

import (
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"

	"github.com/RomanAgaltsev/chaotic/adapter/httpsrv"
	"github.com/RomanAgaltsev/chaotic/engine"
	"github.com/RomanAgaltsev/chaotic/fault"
)

func main() {
	eng := engine.New().AddRule(engine.NewRule(
		engine.MatchKind(engine.OpHTTPServer),
		engine.Times(1),
		engine.WithFault(fault.Error(errors.New("overloaded"))),
	).Named("inbound"))

	var h http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, _ = fmt.Fprintln(w, "handled")
	})
	h = httpsrv.Middleware(eng)(h)

	srv := httptest.NewServer(h)
	defer srv.Close()

	get := func() int {
		resp, err := http.Get(srv.URL)
		if err != nil {
			return -1
		}
		defer func() { _ = resp.Body.Close() }()
		_, _ = io.Copy(io.Discard, resp.Body)
		return resp.StatusCode
	}

	fmt.Println("request 1 status:", get()) // chaos fault -> 500 before the handler
	fmt.Println("request 2 status:", get()) // chaos exhausted -> handler runs
}
Output:
request 1 status: 500
request 2 status: 200
Example (HttpStatus)
package main

import (
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"

	"github.com/RomanAgaltsev/chaotic/adapter/httpsrv"
	"github.com/RomanAgaltsev/chaotic/engine"
	"github.com/RomanAgaltsev/chaotic/fault"
)

func main() {
	eng := engine.New().AddRule(engine.NewRule(
		engine.MatchKind(engine.OpHTTPServer),
		engine.WithFault(fault.HTTPStatus(503, "overloaded")),
	).Named("degrade"))

	h := httpsrv.Middleware(eng)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, _ = fmt.Fprintln(w, "handler ran")
	}))
	srv := httptest.NewServer(h)
	defer srv.Close()

	resp, _ := http.Get(srv.URL + "/")
	body, _ := io.ReadAll(resp.Body)
	_ = resp.Body.Close()
	fmt.Print(resp.StatusCode, " ", string(body))
}
Output:
503 overloaded

Types

This section is empty.

Jump to

Keyboard shortcuts

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