httpsim

package module
v0.0.0-...-f506387 Latest Latest
Warning

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

Go to latest
Published: Feb 1, 2025 License: MIT Imports: 8 Imported by: 2

README

GoDoc GoReportCard Coverage Status

httpsim

Package httpsim provides an HTTP latency and response simulator middleware that simplifies conditionally adding artificial delays and overwriting responses matching requests by path, headers and query parameters using glob expressions.

resources:
  # Make DELETE requests at path "/specific" return 404 responses (overwrite).
  - path: /specific
    methods: [DELETE] # DELETE requests only
    effect:
      replace:
        status-code: 404
        body: "Specific resource not found"
        headers:
          Content-Type: text/plain
          X-Custom: custom
  - path: /* # This is a glob expression for anything behind the root "/".
    # Any HTTP method
    headers:
      # Match requests only when header
      # "Content-Type" exactly equals "application/javascript".
      - name: "Content-Type"
        values: ["application/javascript"] # This is a glob expression.
    query:
      # Match requests only when query parameter
      # "param" starts with "щы".
      # example: "/?param=щы" is matched.
      # example: "/foo/bar?sid=123&param=щы456" is matched.
      # example: "/foo/bar?sid=123&param=щ" is not matched.
      - parameter: "param"
        values: ["щы*"] # This is a glob expression.
    effect:
      # Simulate latency for matched requests by
      # applying a 200-1000 millisecond delay.
      delay:
        min: 200ms
        max: 1s

Middleware

Example of using httpsim as middleware:

// Use httpsim middleware for simulating error responses and delays.
httpsimConf, err := httpsim.LoadConfigFile("httpsim.yaml")
if err != nil {
	panic(err)
}
// Wrap your HTTP handler.
withHTTPSim := httpsim.NewMiddleware(
	yourHandler, *httpsimConf, httpsim.DefaultSleep, httpsim.DefaultRand,
)
err = http.ListenAndServe(":8080", withHTTPSim)

See github.com/gobwas/glob for how to use globs.

Documentation

Overview

Package httpsim provides an HTTP simulator middleware that simplifies conditionally adding artificial delays and overwriting responses matching requests by path, headers and query parameters using glob expressions.

Index

Constants

View Source
const DefaultRand defaultRand = 1

DefaultRand is the default ChaCha8 randomness provider based on a crypto-random seed.

View Source
const DefaultSleep defaultSleep = 1

DefaultSleep is the default system sleep `time.Sleep`.

Variables

This section is empty.

Functions

func Match

func Match(r *http.Request, c *config.Config) int

Match returns the index of the matched resource, otherwise returns -1.

func MatchResource

func MatchResource(r *http.Request, c *config.Resource) bool

MatchResource returns true if r matches resource c, otherwise returns false.

Types

type Config

type Config = config.Config

func LoadConfig

func LoadConfig(src io.Reader) (*Config, error)

LoadConfig loads config from arbitrary reader.

func LoadConfigFile

func LoadConfigFile(file string) (*Config, error)

LoadConfigFile loads config from file.

type CtxInfo

type CtxInfo struct {
	MatchedResourceIndex int
	Delay                time.Duration
	Replaced             bool
}

CtxInfo is written to the request context after handling.

func CtxInfoValue

func CtxInfoValue(ctx context.Context) (info CtxInfo)

CtxInfoValue gets the `CtxInfo` from ctx.

type CtxKey

type CtxKey int8

CtxKey is a context.Context key type.

const CtxKeyInfo CtxKey = 1

CtxKeyInfo is used by CtxInfoValue to get `CtxInfo` from `context.Context`.

type Middleware

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

Middleware implements the http.Handler interface.

func NewMiddleware

func NewMiddleware(
	next http.Handler, c config.Config, sleeper Sleeper, rnd RandProvider,
) *Middleware

NewMiddleware creates a new middleware instance. Use `DefaultSleep` for sleeper (other implementations of Sleeper should only be used for testing purposes). Use `DefaultRand` for rnd if not sure.

func (*Middleware) ServeHTTP

func (m *Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Middleware) SetConfig

func (m *Middleware) SetConfig(c config.Config)

SetConfig changes the configuration of the middleware. SetConfig is safe for concurrent use at runtime.

type RandProvider

type RandProvider interface {
	// Dur returns a random duration within the given min and max range.
	Dur(min, max time.Duration) time.Duration
	// Bool returns a random boolean value.
	Bool() bool
}

RandProvider is a random values generator.

type Seed

type Seed rand.Seed

Seed is a randomness seed.

func NewSeed

func NewSeed(s string) Seed

NewSeed creates a fixed seed from a 32-byte long string. NewSeed panics if s isn't 32-byte long.

func NewSeedRand

func NewSeedRand() Seed

NewSeedRand creates a new random seed from `crypto/rand.Read`.

type Sleeper

type Sleeper interface{ Sleep(time.Duration) }

Sleeper is an abstract sleep. Use `DefaultSleep` for `time.Sleep`.

Directories

Path Synopsis
httpsim
internal
rand
Package rand is a helper package wrapping std lib functions.
Package rand is a helper package wrapping std lib functions.

Jump to

Keyboard shortcuts

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