本文主要研究一下dapr的Pipelinegit
dapr/pkg/middleware/http/http_pipeline.gogithub
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.goapi
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。數組