github.com/sandwich-go/boost@v1.3.29/middleware/middleware.go (about)

     1  package middleware
     2  
     3  import (
     4  	"context"
     5  )
     6  
     7  type (
     8  	// Handler 处理器
     9  	Handler func(context.Context) error
    10  	// Middleware 中间件
    11  	Middleware func(ctx context.Context, next Handler) error
    12  	// Middlewares 中间件集合
    13  	Middlewares []Middleware
    14  )
    15  
    16  // Chain 中间件链
    17  func Chain(middlewares ...Middleware) Middleware {
    18  	n := len(middlewares)
    19  	return func(ctx context.Context, next Handler) error {
    20  		chain := func(currMiddleware Middleware, currHandler Handler) Handler {
    21  			return func(currCtx context.Context) error {
    22  				return currMiddleware(currCtx, currHandler)
    23  			}
    24  		}
    25  		chainHandler := next
    26  		for i := n - 1; i >= 0; i-- {
    27  			if middlewares[i] == nil {
    28  				continue
    29  			}
    30  			chainHandler = chain(middlewares[i], chainHandler)
    31  		}
    32  		return chainHandler(ctx)
    33  	}
    34  }
    35  
    36  // Use 中间件链
    37  func Use(first Middleware, middlewares ...Middleware) Middleware {
    38  	if first == nil {
    39  		first = Chain(middlewares...)
    40  	} else {
    41  		first = Chain(first, Chain(middlewares...))
    42  	}
    43  	return first
    44  }