middleware

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 24, 2023 License: Apache-2.0 Imports: 1 Imported by: 2

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Handler

type Handler func(ctx context.Context, req interface{}) (interface{}, error)

Handler is a function that handles a request.

type Middleware

type Middleware func(Handler) Handler

Middleware is a chainable behavior modifier for handlers.

func Chain

func Chain(mws ...Middleware) Middleware

Chain returns a middleware that chains the passed middlewares.

Example
package main

import (
	"context"
	"fmt"
)

func main() {
	e := Chain(
		annotate("first"),
		annotate("second"),
		annotate("third"),
	)(myHandler)

	if _, err := e(ctx, req); err != nil {
		panic(err)
	}

}

var (
	ctx = context.Background()
	req = struct{}{}
)

func annotate(s string) Middleware {
	return func(next Handler) Handler {
		return func(ctx context.Context, request interface{}) (interface{}, error) {
			fmt.Println(s, "pre")
			defer fmt.Println(s, "post")
			return next(ctx, request)
		}
	}
}

func myHandler(context.Context, interface{}) (interface{}, error) {
	fmt.Println("my handler!")
	return struct{}{}, nil
}
Output:

first pre
second pre
third pre
my handler!
third post
second post
first post

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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