github.com/aacfactory/fns@v1.2.86-0.20240310083819-80d667fc0a17/transports/middleware.go (about)

     1  /*
     2   * Copyright 2023 Wang Min Xiang
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   * 	http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   *
    16   */
    17  
    18  package transports
    19  
    20  import (
    21  	"github.com/aacfactory/configures"
    22  	"github.com/aacfactory/errors"
    23  	"github.com/aacfactory/logs"
    24  	"io"
    25  	"strings"
    26  )
    27  
    28  type MiddlewareOptions struct {
    29  	Log    logs.Logger
    30  	Config configures.Config
    31  }
    32  
    33  type Middleware interface {
    34  	Name() string
    35  	Construct(options MiddlewareOptions) error
    36  	Handler(next Handler) Handler
    37  	io.Closer
    38  }
    39  
    40  func WaveMiddlewares(log logs.Logger, config Config, middlewares []Middleware) (v Middlewares, err error) {
    41  	for _, middleware := range middlewares {
    42  		name := strings.TrimSpace(middleware.Name())
    43  		mc, mcErr := config.MiddlewareConfig(name)
    44  		if mcErr != nil {
    45  			err = errors.Warning("wave middlewares failed").WithCause(mcErr).WithMeta("middleware", name)
    46  			return
    47  		}
    48  		constructErr := middleware.Construct(MiddlewareOptions{
    49  			Log:    log.With("middleware", name),
    50  			Config: mc,
    51  		})
    52  		if constructErr != nil {
    53  			err = errors.Warning("wave middlewares failed").WithCause(constructErr).WithMeta("middleware", name)
    54  			return
    55  		}
    56  	}
    57  	v = middlewares
    58  	return
    59  }
    60  
    61  type Middlewares []Middleware
    62  
    63  func (middlewares Middlewares) Handler(handler Handler) Handler {
    64  	if len(middlewares) == 0 {
    65  		return handler
    66  	}
    67  	for i := len(middlewares) - 1; i > -1; i-- {
    68  		handler = middlewares[i].Handler(handler)
    69  	}
    70  	return handler
    71  }
    72  
    73  func (middlewares Middlewares) Close() {
    74  	for _, middleware := range middlewares {
    75  		_ = middleware.Close()
    76  	}
    77  	return
    78  }