middleware

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2023 License: MIT Imports: 0 Imported by: 0

Documentation

Overview

Package middleware implements middleware architecture pattern to use in generic way. It's used to create delegates for processing the request or response and handle common tasks like logging, authentication, compressing data in single contact point which is called pipeline.

Example
package main

import (
	"errors"
	"fmt"

	"github.com/Prastiwar/Go-flow/middleware"
)

func main() {
	type pipeRequest string
	type pipeResponse error

	// middleware pipeline for request of type 'pipeRequest' and response of type 'pipeResponse'
	middleware := middleware.NewMiddleware[pipeRequest, pipeResponse]()

	middleware.Use(
		func(r pipeRequest, next func(r pipeRequest) pipeResponse) pipeResponse {
			fmt.Println("1")
			response := next(r)
			fmt.Println("4")
			return response
		},
	)

	middleware.Use(
		func(r pipeRequest, next func(r pipeRequest) pipeResponse) pipeResponse {
			fmt.Println("2")
			validate := func(r pipeRequest) bool { return true }

			ok := validate(r)
			if !ok {
				// stop pipeline and return error
				return errors.New("validation failed")
			}
			return next(r)
		},
	)

	handler := func(r pipeRequest) pipeResponse {
		fmt.Println("3")
		return nil
	}

	// wrap middleware to handler
	wrappedHandler := middleware.Wrap(handler)
	request := pipeRequest("request")

	// run pipeline
	response := wrappedHandler(request)
	fmt.Println("Response:", response)

}
Output:

1
2
3
4
Response: <nil>

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Middleware

type Middleware[Request any, Response any] interface {
	Wrap(func(r Request) Response) func(r Request) Response

	Use(pipe func(r Request, next func(r Request) Response) Response)
}

Middleware is implemented by any value that has a Wrap and Use method. The implementation provides a way to build pipeline over specifiec function and store pipes using simple Use method.

func NewMiddleware

func NewMiddleware[Request any, Response any]() Middleware[Request, Response]

NewMiddleware returns a new generic middleware instance.

Jump to

Keyboard shortcuts

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