block

package
v0.18.2 Latest Latest
Warning

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

Go to latest
Published: Jun 11, 2026 License: MIT Imports: 2 Imported by: 1

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Block

type Block struct {
	Match func(r *http.Request) bool
	// contains filtered or unexported fields
}

Block is middleware block

func New

func New(match func(r *http.Request) bool) *Block

New creates news block

Example

Apply an inner middleware chain only to requests the Match predicate selects; every other request falls through to the rest of the server untouched. Here, requests under /api get their own rate limit and an extra request header.

package main

import (
	"net/http"
	"strings"

	"github.com/moonrhythm/parapet"
	"github.com/moonrhythm/parapet/pkg/block"
	"github.com/moonrhythm/parapet/pkg/headers"
	"github.com/moonrhythm/parapet/pkg/ratelimit"
)

func main() {
	b := block.New(func(r *http.Request) bool {
		return strings.HasPrefix(r.URL.Path, "/api/")
	})
	b.Use(ratelimit.FixedWindowPerSecond(20))
	b.Use(headers.SetRequest("X-Scope", "api"))

	s := parapet.New()
	s.Use(b)
	// s.Use(upstream.SingleHost("10.0.0.1:8080")) — handles both matched and
	// unmatched requests; the block only adds behavior for the matched ones.
}
Example (CatchAll)

A nil Match makes the Block a catch-all: its inner chain runs for every request. This is a convenient way to group a sub-chain as a single Middleware.

package main

import (
	"github.com/moonrhythm/parapet"
	"github.com/moonrhythm/parapet/pkg/block"
	"github.com/moonrhythm/parapet/pkg/headers"
)

func main() {
	b := block.New(nil)
	b.Use(headers.SetResponse("X-Served-By", "edge"))

	s := parapet.New()
	s.Use(b)
}

func (*Block) ServeHandler

func (b *Block) ServeHandler(h http.Handler) http.Handler

ServeHandler implements middleware interface

func (*Block) Use

func (b *Block) Use(m parapet.Middleware)

Use uses middleware

func (*Block) UseFunc added in v0.13.2

func (b *Block) UseFunc(m parapet.MiddlewareFunc)
Example

UseFunc adds an inline MiddlewareFunc to the block's inner chain without declaring a named Middleware type.

package main

import (
	"net/http"

	"github.com/moonrhythm/parapet"
	"github.com/moonrhythm/parapet/pkg/block"
)

func main() {
	b := block.New(func(r *http.Request) bool {
		return r.Method == http.MethodPost
	})
	b.UseFunc(func(h http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			r.Header.Set("X-Write", "true")
			h.ServeHTTP(w, r)
		})
	})

	s := parapet.New()
	s.Use(b)
}

Jump to

Keyboard shortcuts

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