序
本文次要钻研一下 dapr 的 Pipeline
Pipeline
dapr/pkg/middleware/http/http_pipeline.go
import (
"github.com/dapr/dapr/pkg/config"
"github.com/valyala/fasthttp"
)
type Middleware func(h fasthttp.RequestHandler) fasthttp.RequestHandler
// HTTPPipeline defines the middleware pipeline to be plugged into Dapr sidecar
type Pipeline struct {Handlers []Middleware
}
func BuildHTTPPipeline(spec config.PipelineSpec) (Pipeline, error) {return Pipeline{}, nil
}
func (p Pipeline) Apply(handler fasthttp.RequestHandler) fasthttp.RequestHandler {for i := len(p.Handlers) - 1; i >= 0; i-- {handler = p.Handlers[i](handler)
}
return handler
}
Pipeline 定义了 Handlers 属性,是一个 Middleware 数组;Pipeline 定义了 Apply 办法,它会从后往前挨个执行 Middleware 函数;Middleware 函数接管 fasthttp.RequestHandler,返回 fasthttp.RequestHandler
实例
dapr/pkg/http/server.go
type server struct {
config ServerConfig
tracingSpec config.TracingSpec
metricSpec config.MetricSpec
pipeline http_middleware.Pipeline
api API
}
func (s *server) useComponents(next fasthttp.RequestHandler) fasthttp.RequestHandler {return s.pipeline.Apply(next)
}
server 定义了 pipeline 属性,其 useComponents 办法接管 fasthttp.RequestHandler),对其执行 pipeline.Apply
小结
dapr 的 Pipeline 定义了 Handlers 属性,是一个 Middleware 数组;Pipeline 定义了 Apply 办法,它会从后往前挨个执行 Middleware 函数;Middleware 函数接管 fasthttp.RequestHandler,返回 fasthttp.RequestHandler。
doc
- dapr